Given an array and target value, to find a few numbers and the target value.
In dfs, the input parameters are: total result, current digital record, current digital sum, array, array subscript, target value.
If the current sum exceeds target, exit dfs
If the current sum == target, record the result
meaning of the title
Given an array and target, find all combinations, in which the numbers can be reused, and there are no repeated numbers in the array
analyze
http://www.zhimengzhe.com/bianchengjiaocheng/Javabiancheng/257227.html
Summary of backtracking
code
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
if(candidates == null || candidates.length <= 0 || target < 0) return result;
dfs(result,temp,candidates,0,0,target);
return result;
}
public void dfs(List<List<Integer>> result,List<Integer> temp,int[] nums,int pos,int curSum,int target){
//1. Exit the loop directly
if (curSum > target) return;
//2. Result situation
if (curSum == target) {
result.add(new ArrayList<Integer>(temp));
}
//3. Ordinary case --- selection condition: because the number can be used repeatedly without repetition, it can be used from pos to the end
//4. Whether to backtrack---because the distance is recorded, the previous choice needs to be eliminated when making the next choice.
for (int i=pos; i < nums.length; i++) {
temp.add(nums[i]);
curSum+=nums[i];
dfs(result,temp,nums,i,curSum,target);
temp.remove(temp.size() - 1);
curSum = nums[i];
}
}
}