39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[ [7], [2, 2, 3] ]

 此题的思路可参考「数组的子集」:https://www.cnblogs.com/MarkLeeBYR/p/16887119.html

public List<List<Integer>> combinationSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
Arrays.sort(nums);
backtrack(list, temp, nums, target, 0);
return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> temp, int [] nums, int remian, int start) {
if (remian < 0)
return;
else if (remian == 0) {
list.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]);
backtrack(list, temp, nums, remian - nums[i], i); //不是i加1,因为可以重复的用元素, 和其他回溯问题的区别:不能传start,必须是i。因为不能走“回头路”,比如2,3,5,target=7,选完3之后,第二轮不会再回过头来选2了
temp.remove(temp.size() - 1);
}
}
posted @ 2022-11-06 16:11  MarkLeeBYR  阅读(28)  评论(0)    收藏  举报