您的位置:首页 > 其它

Combination Sum II

2015-07-23 09:20 281 查看
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相比的唯一变化就是每个数字只能使用一次,这样在DFS中递归

下一个元素。同时不能有重复结果,可以先放到set中,再从set返回结果。

Combination Sum中没有这个处理也通过OJ,应该是测试用例没有考虑到这个问题。

public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
ArrayList<List<Integer>> at=new ArrayList<List<Integer>>();
if(candidates==null||candidates.length<=0)
return at;
List<Integer> lt=new ArrayList<Integer>();
Arrays.sort(candidates);
combinationSum2(candidates, target,0,at,lt);
HashSet<List<Integer>> ht=new HashSet<List<Integer>>(at);
at.clear();
at.addAll(ht);
return at;
}
public static void combinationSum2(int[] arr,int target,int j,ArrayList<List<Integer>> at,
List<Integer> lt){
if(target==0){
List<Integer> t=new ArrayList<Integer>(lt);
at.add(t);
return;
}
for(int i=j;i<arr.length;i++){
if(arr[i]>target)
return;
lt.add(arr[i]);
combinationSum2(arr, target-arr[i], i+1, at, lt);
lt.remove(lt.size()-1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: