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]
]
解法
回溯法,先对数组进行排序,每次添加本元素及本元素之后的内容。注意ret.add(new ArrayList(temp));要重新new一个list。
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ret = new ArrayList<>();
if (candidates == null || candidates.length == 0 || target <= 0) {
return ret;
}
Arrays.sort(candidates);
backtrack(ret, new ArrayList<Integer>(), candidates, target, 0);
return ret;
}
private void backtrack(List<List<Integer>> ret, List<Integer> temp, int[] candidates, int remain, int start) {
if (remain == 0) {
ret.add(new ArrayList<Integer>(temp));
} else if (remain < 0) {
return;
}
for (int i = start; i < candidates.length; i++) {
temp.add(candidates[i]);
backtrack(ret, temp, candidates, remain - candidates[i], i);
temp.remove(temp.size() - 1);
}
}
}