您的位置:首页 > 其它

Combination Sum II

2015-05-31 09:54 579 查看
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.
Elements in a combination (a1, a2,
… , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
… ≤ ak).
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的区别是要考虑到去重,因为数字可能会重复,那么选出的两个子集合也可能会重复。考虑去重的话,就是在当前元素被删除的时候,也就是当前元素没有被选中,如果下一个数字与当前数字是相同的,那选择下一个数字也是没有意义的,直接跳过下一个数字,从下下个数字开始选择。

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res =new ArrayList<List<Integer>>();
select_sum(candidates,0,target,new ArrayList<Integer>(),res);
return res;
}
//从candidates中选出数字使得所选出数字的和为target,temp作为所选出数字的临时栈,idx代表candidates的下标
public  void select_sum(int[] candidates, int idx, int target,List<Integer> temp, List<List<Integer>> res) {
if (target<0)
return;
//如果target,说明所选出数字的和为target,就将temp添加到res中
if (target==0) {
List<Integer> temp_new = new ArrayList<Integer>(temp);
if(temp_new.size()==0) return;
res.add(temp_new);
return;
}
if (idx >= candidates.length)
return;
//如果当前数字被选中,下标应该从idx+1开始,选出的剩下的数字的和为target-candidates[idx]
temp.add(candidates[idx]);
select_sum(candidates, idx+1, target-candidates[idx], temp, res);
//如果当前数字没有被选中,删除已经添加进去的数字,那就从下一个数字开始选择
temp.remove(temp.size() - 1);
//但是如果下一个数字和当前没有被选中的数字相等的话,那就直接跳过下一个数字,也就是去重
while(idx<candidates.length-1&&candidates[idx+1]==candidates[idx])
idx++;
select_sum(candidates, idx+1, target, temp, res);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: