forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path_40.java
More file actions
57 lines (48 loc) · 1.93 KB
/
_40.java
File metadata and controls
57 lines (48 loc) · 1.93 KB
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
package com.fishercoder.solutions;
import com.fishercoder.common.utils.CommonUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/***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]
]*/
public class _40 {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList();
Arrays.sort(candidates);
helper(candidates, target, 0, new ArrayList(), result);
return result;
}
void helper(int[] candidates, int target, int start, List<Integer> curr, List<List<Integer>> result) {
if (target > 0) {
for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;//skip duplicates, this is one difference from Combination Sum I
}
curr.add(candidates[i]);
helper(candidates, target - candidates[i], i + 1, curr, result);//i+1 is the other difference from Combination Sum I
curr.remove(curr.size() - 1);
}
} else if (target == 0) {
List<Integer> temp = new ArrayList(curr);
result.add(temp);
}
}
public static void main(String... args) {
_40 test = new _40();
int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};
int target = 8;
List<List<Integer>> result = test.combinationSum2(candidates, target);
CommonUtils.printListList(result);
}
}