题意:
给出一列不重复的数字,从中选取一组数字,其和为目标数(每个数可以选取0到无穷次),返回所有可能的组合。
分析:
这是一道搜索题,先画出搜索树。
2 3 6 7
2 3 6 7 2 3 6 7 2 3 6 7 2 3 6 7
递归深搜,每层范围是数组全部,结束条件是等于大于和,满足条件是等于和。
然后写出来发现搜索树写错了,因为不同顺序算一种,所以多设置一个参数s,每次只遍历自己之后的:
public class Solution {
List<Integer> l = null;
List<List<Integer>> list = null;
int target = 0;
int[] candidates;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
l = new ArrayList<>();
list = new ArrayList<>();
this.target = target;
this.candidates = candidates;
for(int i=0; i<candidates.length; i++){
l.add(candidates[i]);
helper(i, candidates[i]);
l.remove(l.size()-1);
}
return list;
}
private void helper(int s, int sum){
if(sum >= target){
if(target == sum){
list.add(new ArrayList(l));
}
return;
}
for(int i=s; i<candidates.length; i++){
l.add(candidates[i]);
helper(i, sum+candidates[i]);
l.remove(l.size()-1);
}
}
}