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]
]
首先排序是必须的,这没什么好说的
1.想到递归,每一层筛选出一个合理的数,并获得新的target值
2.每一层都要维护一个属于自己的list,传递给下一层的时候创建新的list进行传递(非常重要,每层维护的list容易混淆)
3.后一层都要从前一层选中的数的标号开始往后查找,并且要跳过前后两个数相同的坐标,这样避免出现重复
ps:貌似可以使用深度搜索做.目测效率不高,没有尝试
java代码如下
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> lists = new ArrayList<List<Integer>>();
combineSum(candidates, 0, target, lists, null);
return lists;
}
public void combineSum(int[] candidates, int begin,int target,List<List<Integer>> lists,List<Integer> list) {
for (int i = begin; i < candidates.length; i++) {
if (i > 0 && candidates[i] == candidates[i - 1]) {
continue;
}
int now = candidates[i];
if (now == target) {
if (list == null) {
list = new ArrayList<Integer>();
}
List<Integer> integerList = new ArrayList<Integer>(list);
integerList.add(now);
lists.add(integerList);
continue;
}
if (now * 2 <= target) { //两倍的值小于目标值
if (list == null) {
list = new ArrayList<Integer>();
}
List<Integer> integerList = new ArrayList<Integer>(list);
integerList.add(now);
combineSum(candidates,i,target - now,lists,integerList);
}
}
}
}