- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSumII.java
More file actions
Latest commit
54 lines (42 loc) · 1.7 KB
/
Copy pathCombinationSumII.java
File metadata and controls
54 lines (42 loc) · 1.7 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
importjava.util.ArrayList;
importjava.util.List;
publicclassCombinationSumII {
/**
*
* Given a collection of candidate numbers (candidates) and a target number (target),
* find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates 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.
Time: O(2^n)
space: O(n)
*/
publicList<List<Integer>> combinationSum2(int[] candidates, inttarget) {
List<List<Integer>> res = newArrayList<List<Integer>>();
helper(candidates, target, 0, newArrayList<>(), res, 0);
returnres;
}
publicvoidhelper(int[] candidates, inttarget, intcur, List<Integer> list, List<List<Integer>> res, intsum) {
if(sum == target) {
res.add(newArrayList<>(list));
return;
}
if(sum < target) {
for(inti = cur; i < candidates.length; i++) {
if(i != cur && candidates[i] == candidates[i - 1]) continue;
//When it goes to next level, it could have duplicates, but not in the same level!!
sum += candidates[i];
list.add(candidates[i]);
helper(candidates, target, i + 1, list, res, sum);
list.remove(list.size() - 1);
sum -= candidates[i];
}
}
}
publicstaticvoidmain(String[] args) {
CombinationSumIIa = newCombinationSumII();
int[] b = {10,1,2,7,6,1,5};
System.out.println(a.combinationSum2(b,8));
}
}