Given a set of candidate numbers (C) 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] ]
----------------------------------------------------------------------------------------------------
我们还是利用回溯的思想来处理这个问题。
重点要注意几点:
1. 恢复现场!这是做回溯问题千万不能忘记的。
2. 此题目中每个数都可以被重复使用。
重复使用意味着:
下阶段可以取跟上阶段一样的元素。
3. 不允许出现重复的组合。
强调不允许出现重复的组合意味着:
在当前阶段:如果1 已经去递归回溯过了,如果下一次元素还是1的话,不要再进行递归回溯了。
运行时间:
代码:
public class CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
doCombinationSum(result, new ArrayList<>(), 0, candidates, target);
return result;
}
private void doCombinationSum(List<List<Integer>> result, List<Integer> curList, int index, int[] candidates, int curSum) {
if (curSum < 0) {
return;
}
if (curSum == 0) {
result.add(new ArrayList<>(curList));
return;
}
for (int i = index; i < candidates.length; i++) {
// avoid duplication
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
curList.add(candidates[i]);
doCombinationSum(result, curList, i, candidates, curSum - candidates[i]);
// recover to origin
curList.remove(curList.size() - 1);
}
}
}