class Solution {
private static int target = 0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.target = target;
List<List<Integer>> listAll = new ArrayList<>();
List<Integer> list = new ArrayList<>();
Arrays.sort(candidates);
find(listAll, list, candidates, target, 0);
return listAll;
}
public void find(List<List<Integer>> list, List<Integer> tmp, int[] candidates, int target, int num) {
if (target==0) {
listAdd(list,tmp,this.target);
return;
}
if (target < candidates[0]) {
return;
}
for (int i = num; i < candidates.length && candidates[i] <= target; i++) {
List<Integer> sub = new ArrayList<>(tmp);
sub.add(candidates[i]);
find(list, sub, candidates, target-candidates[i], i);
}
}
public void listAdd(List<List<Integer>> list, List<Integer> tmp, int target) {
if (sum(tmp) == target) {
List<Integer> sub = new ArrayList<>(tmp);
list.add(sub);
}
}
public int sum(List<Integer> tmp) {
return tmp.stream().mapToInt(o -> o).sum();
}
}
【leetcode】39. 组合总和
最新推荐文章于 2024-06-17 11:07:07 发布