-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombination Sum II
58 lines (47 loc) · 1.95 KB
/
Combination Sum II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class Solution {
private LinkedList<LinkedList<Integer>> results=new LinkedList<LinkedList<Integer>>();
public LinkedList<LinkedList<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
LinkedList<Integer> solution=new LinkedList<Integer>();
helper(candidates, 0, target, solution);
return results;
}
private void helper(int[] candidates, int k, int target, LinkedList<Integer> solution) {
if (target<0) return;
if (target==0) {
LinkedList<Integer> res=new LinkedList<Integer>(solution);
results.add(res);
return;
}
for (int i=k; i<candidates.length; i++) {
solution.add(candidates[i]);
helper(candidates, i+1, target-candidates[i], solution);
solution.remove(solution.size()-1);
while ((i<candidates.length-1)&&(candidates[i+1]==candidates[i])) i++;
}
}
}
///////////////////////////////////////////Another solution
public class Solution {
private LinkedList<LinkedList<Integer>> results=new LinkedList<LinkedList<Integer>>();
public LinkedList<LinkedList<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
LinkedList<Integer> solution=new LinkedList<Integer>();
helper(candidates, 0, target, solution);
return results;
}
private void helper(int[] candidates, int k, int target, LinkedList<Integer> solution) {
if (target<0) return;
if (target==0) {
LinkedList<Integer> res=new LinkedList<Integer>(solution);
results.add(res);
return;
}
for (int i=k; i<candidates.length; i++) {
if ((i!=k)&&(candidates[i]==candidates[i-1])) continue;
solution.add(candidates[i]);
helper(candidates, i+1, target-candidates[i], solution);
solution.remove(solution.size()-1);
}
}
}