Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
在combination基础上刷这道题,主要是递归层数这个地方。
for(int i = n; i < candidates.length; i++){
list.add(candidates[i]);
helper(candidates, target - candidates[i], results, list, i);
list.remove(list.size() - 1);
}
否则出现如下报错:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
helper(candidates, target, results, list, 0);
return results;
}
public void helper(int[] candidates, int target,
List<List<Integer>> results, List<Integer> list, int n){
if(target < 0)
return;
if(target == 0){
results.add(new ArrayList<Integer>(list));
return;
}
for(int i = n; i < candidates.length; i++){
list.add(candidates[i]);
helper(candidates, target - candidates[i], results, list, i);
list.remove(list.size() - 1);
}
}
}