39. Combination Sum 凑出一个和,可以重复用元素(含duplicates)
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7],
target = 7
,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5],
target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
可以不从第0位开始,直接从start开始。DFS中应该有start这个参数
循环里面当然是用i,不是start
需要考虑currentSum > target然后就会直接return ;的这种情况
和subset、全排列不同,这里的元素可以重复用。所以不需要
if(temp.contains(nums[i])) continue;
class Solution { public List<List<Integer>> combinationSum(int[] nums, int target) { //cc List<List<Integer>> results = new ArrayList<List<Integer>>(); if (nums == null || nums.length == 0) return results; //排序一下 Arrays.sort(nums); backtrace(nums, new ArrayList<Integer>(), 0, 0, target, results); return results; } public void backtrace(int[] nums, List<Integer> temp, int start, int currentSum, int target, List<List<Integer>> results) { //exit if (currentSum == target) { results.add(new ArrayList<>(temp)); //必须这样写 }else if (currentSum > target) { return ; }else { for (int i = start; i < nums.length; i++) { temp.add(nums[i]); backtrace(nums, temp, i, currentSum + nums[i], target, results); temp.remove(temp.size() - 1); } } } }