1 问题
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]
]
2 分析
如果对输入不做处理,所有可能出现的数字组合有 C1n+C2n+...+Cnn 种,将其中每一个与target
比较,时间复杂度是指数级别的。
但是该问题蕴含着数字的大小、相等关系,因此需要利用这种内在的数字关系来提高算法的运行效率。
为此,将输入的数组进行排序,排序算法的时间复杂度是O(nlogn)。排序之后,整个解法的计算过程如图所示:
设输入的数组用 a1,a2,...,an 表示。上图中,树的结点表示所有可能与target
相等的组合,层数等于可能的组合中的数字个数。令 Sn 表示每个节点中所有元素的和,因此:
- 如果Sn≤target 该节点存在子节点,继续按照图示规律访问子节点;
- 如果Sn>target ,该节点为叶子,应当回溯回父节点。
在所有可能的组合遍历完成后,与target
相等的组合会被记录下来。
该算法的时间复杂度为树中所有节点的数目,与题目所给输入值有关。
3 代码
递归+回溯:
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
getResult(result, new ArrayList<Integer>(), candidates, target, 0);
return result;
}
private boolean getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
if(target == 0){
result.add(new ArrayList<Integer>(cur));
return true;
}else if(target < 0){
return false;
}else{
for(int i = start; i < candidates.length && target >= candidates[i]; i++){
cur.add(candidates[i]);
boolean res = getResult(result, cur, candidates, target - candidates[i], i);
if(!res){
return false;
}
cur.remove(cur.size() - 1);
}
return true;
}
}
}