题目
题目I
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.
题目II
Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
分析
题目I是在一个没有重复数字,但是数字可以重复选择的数组中找到所有累加和为target的集合,集合中不考虑位置且结果不能有重复。
题目II是在一个有重复数字,但是每个数字只能选择一次的数组中找到所有累加和为target的集合,集合中不考虑位置且结果不能有重复。
还有一种动态规划解法,这里先用回溯。
代码
I
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList();
combinationSum(candidates, target, new ArrayList(), res, 0);
return res;
}
private void combinationSum(int[] candidates, int target, List<Integer> list, List<List<Integer>> res, int start){
if(target > 0){
for(int i = start; i < candidates.length; ++i){
list.add(candidates[i]);
//回溯还是从i开始,因为可以重复选取。
combinationSum(candidates, target - candidates[i], list, res, i);
list.remove(list.size() - 1);
}
}else if(target == 0){
res.add(new ArrayList(list));
}
}
II
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates); //先排序
List<List<Integer>> res = new ArrayList();
if(candidates == null || candidates.length == 0 || target <= 0) return res;
helper(candidates, res, new ArrayList(), target, 0);
return res;
}
public void helper(int[] candidates, List<List<Integer>> res, List<Integer> list, int target, int start){
if(target == 0){
res.add(new ArrayList(list));
}else if(target > 0){
for(int i = start; i < candidates.length; ++i){
if(i > start && candidates[i] == candidates[i-1]){ //防止重复,I不存在这个问题
continue;
}
list.add(candidates[i]);
helper(candidates, res, list, target - candidates[i], i + 1);//从下一个数开始
list.remove(list.size() - 1);
}
}
}