5
5
import java .util .ArrayList ;
6
6
import java .util .Arrays ;
7
7
import java .util .List ;
8
- /***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.
9
-
10
- Each number in C may only be used once in the combination.
8
+ /**
9
+ * 40. Combination Sum II
10
+ *
11
+ * 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.
12
+ * Each number in C may only be used once in the combination.
11
13
12
14
Note:
13
15
All numbers (including target) will be positive integers.
@@ -19,24 +21,25 @@ All numbers (including target) will be positive integers.
19
21
[1, 2, 5],
20
22
[2, 6],
21
23
[1, 1, 6]
22
- ]*/
24
+ ]
25
+ */
23
26
public class _40 {
24
27
25
28
public List <List <Integer >> combinationSum2 (int [] candidates , int target ) {
26
29
List <List <Integer >> result = new ArrayList ();
27
30
Arrays .sort (candidates );
28
- helper (candidates , target , 0 , new ArrayList (), result );
31
+ backtracking (candidates , target , 0 , new ArrayList (), result );
29
32
return result ;
30
33
}
31
34
32
- void helper (int [] candidates , int target , int start , List <Integer > curr , List <List <Integer >> result ) {
35
+ void backtracking (int [] candidates , int target , int start , List <Integer > curr , List <List <Integer >> result ) {
33
36
if (target > 0 ) {
34
37
for (int i = start ; i < candidates .length && target >= candidates [i ]; i ++) {
35
38
if (i > start && candidates [i ] == candidates [i - 1 ]) {
36
39
continue ;//skip duplicates, this is one difference from Combination Sum I
37
40
}
38
41
curr .add (candidates [i ]);
39
- helper (candidates , target - candidates [i ], i + 1 , curr , result );//i+1 is the other difference from Combination Sum I
42
+ backtracking (candidates , target - candidates [i ], i + 1 , curr , result );//i+1 is the other difference from Combination Sum I
40
43
curr .remove (curr .size () - 1 );
41
44
}
42
45
} else if (target == 0 ) {
@@ -53,5 +56,4 @@ public static void main(String... args) {
53
56
CommonUtils .printListList (result );
54
57
}
55
58
56
-
57
59
}
0 commit comments