您的位置:首页 > 编程语言 > Java开发

Combination Sum II leetcode java

2014-08-02 00:24 375 查看
题目

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本质的差别就是当前已经遍历过的元素只能出现一次。

所以需要给每个candidate一个visited域,来标识是否已经visited了。

当回退的时候,记得要把visited一起也回退了。

代码如下:

1 public static ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 ArrayList<Integer> item = new ArrayList<Integer>();
4 if(candidates == null || candidates.length==0)
5 return res;
6
7 Arrays.sort(candidates);
8 boolean [] visited = new boolean[candidates.length];
9 helper(candidates,target, 0, item ,res, visited);
return res;
}

private static void helper(int[] candidates, int target, int start, ArrayList<Integer> item,
ArrayList<ArrayList<Integer>> res, boolean[] visited){
if(target<0)
return;
if(target==0){
res.add(new ArrayList<Integer>(item));
return;
}

for(int i=start;i<candidates.length;i++){
if(!visited[i]){
if(i>0 && candidates[i] == candidates[i-1] && visited[i-1]==false)//deal with dupicate
continue;
item.add(candidates[i]);
visited[i]=true;
int newtarget = target - candidates[i];
helper(candidates,newtarget,i+1,item,res,visited);
visited[i]=false;
item.remove(item.size()-1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: