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:
1. All numbers (including target) will be positive integers.
2. 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]
]
注释:给定一个整数数组C和一个目标整数T,找出C中所有组合,使组合之和等于T。数组C中数字可以不限次数使用。
数组C中所有整数都为整数,T亦一样;结果集中不包含重复结果。
假设C是升序排列的,从C中按顺序取出整数存入tmp中,tmp中所有数字之和为sum。
1. 当sum大于T时,不符合条件;
2. 当sum等于T时,符合条件,此时tmp是一个结果集;
3. 当sum小于T时,从C中继续取出数存入tmp中
重复上述步骤,在将整数存入tmp中进行判断后,需要再将该整数从tmp中踢出(回溯法)
以C:[2,3,6,7]和T:7为例进行分析:
初始化:tmp={} sum =0
取2存入tmp,tmp={2}, sum= 2;进行第三步,此时应继续从2开始取值,再次将2存入tmp, tmp= {2,2}, sum = 4 ;再重复第三步两次后,tmp={2,2,2,2} sum= 8,由于sum>T,不符合条件。
此时,需要退回到tmp={2,2,2} sum=6 的状态,重复取后面的值3,6,7;
再次退回tmp={2,2} sum = 4 的状态,取值3之后,tmp={2,2,3} sum = 7,满足sum = T,因此tmp={2,2,3}为一个解。
再以2为开头的所有组合判断完后,需要从3开始继续判断,并且不能有取值为2的组合(所有组合是唯一的)
下面附上实现代码:
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();//存储所有组合
List<Integer> tmp = new ArrayList<Integer>();//存储当前组合
Arrays.sort(candidates);//候选数组排序
findSum(candidates, target, 0, result, tmp, 0);
return result;
}
public void findSum(int[] candidates, int target, int sum, List<List<Integer>> result, List<Integer> tmp, int level){
if(sum > target) {
return ;
}
if (sum == target) {
result.add(new ArrayList<Integer>(tmp));//一定要新建一个数组加入结果集中
return;
}
for(int i = level; i < candidates.length; i++) {
tmp.add(candidates[i]);
findSum(candidates, target, sum+candidates[i], result, tmp, i);
tmp.remove(tmp.size()-1);//需回退到上一个状态
}
}
144

被折叠的 条评论
为什么被折叠?



