为什么80%的码农都做不了架构师?>>>
问题:
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.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
解决:
① 这道题跟Combination Sum非常相似,唯一的区别就是这个题目中单个元素用过就不可以重复使用了。乍一看好像区别比较大,但是其实实现上只需要一点点改动就可以完成了,就是递归的时候传进去的index应该是当前元素的下一个。
class Solution { //17ms
public static List> combinationSum2(int[] candidates, int target){
Arrays.sort(candidates);
List> res = new ArrayList<>();
List
dfs(candidates,0,target,cur,res);
return res;
}
private static void dfs(int[] candidates,int i, int target, List> res) {
if(target < 0) return;
if(target == 0){
res.add(new ArrayList<>(cur));
return;
}
for(int j = i; j < candidates.length && target >= candidates[j]; j ++){
if(j > i && candidates[j] == candidates[j - 1]) continue;//去重,若有两个相同的数,则以它们为开头时,会遍历出相同的值,应当跳过以避免重复
cur.add(candidates[j]);
dfs(candidates,j + 1,target - candidates[j],cur,res);//一个数字只能使用1次
cur.remove(cur.size() - 1);
}
}
}