1
1
package com .fishercoder .solutions ;
2
2
3
- import com .fishercoder .common .utils .CommonUtils ;
4
-
5
3
import java .util .ArrayList ;
6
4
import java .util .Arrays ;
7
5
import java .util .List ;
@@ -25,35 +23,28 @@ All numbers (including target) will be positive integers.
25
23
*/
26
24
public class _40 {
27
25
28
- public List <List <Integer >> combinationSum2 (int [] candidates , int target ) {
29
- List <List <Integer >> result = new ArrayList ();
30
- Arrays .sort (candidates );
31
- backtracking (candidates , target , 0 , new ArrayList (), result );
32
- return result ;
33
- }
26
+ public static class Solution1 {
27
+ public List <List <Integer >> combinationSum2 (int [] candidates , int target ) {
28
+ List <List <Integer >> result = new ArrayList ();
29
+ Arrays .sort (candidates );
30
+ backtracking (candidates , target , 0 , new ArrayList (), result );
31
+ return result ;
32
+ }
34
33
35
- void backtracking (int [] candidates , int target , int start , List <Integer > curr , List <List <Integer >> result ) {
36
- if (target > 0 ) {
37
- for (int i = start ; i < candidates .length && target >= candidates [i ]; i ++) {
38
- if (i > start && candidates [i ] == candidates [i - 1 ]) {
39
- continue ;//skip duplicates, this is one difference from Combination Sum I
34
+ void backtracking (int [] candidates , int target , int start , List <Integer > curr , List <List <Integer >> result ) {
35
+ if (target > 0 ) {
36
+ for (int i = start ; i < candidates .length && target >= candidates [i ]; i ++) {
37
+ if (i > start && candidates [i ] == candidates [i - 1 ]) {
38
+ continue ;//skip duplicates, this is one difference from Combination Sum I
39
+ }
40
+ curr .add (candidates [i ]);
41
+ backtracking (candidates , target - candidates [i ], i + 1 , curr , result );//i+1 is the other difference from Combination Sum I
42
+ curr .remove (curr .size () - 1 );
40
43
}
41
- curr .add (candidates [i ]);
42
- backtracking (candidates , target - candidates [i ], i + 1 , curr , result );//i+1 is the other difference from Combination Sum I
43
- curr .remove (curr .size () - 1 );
44
+ } else if (target == 0 ) {
45
+ result .add (new ArrayList (curr ));
44
46
}
45
- } else if (target == 0 ) {
46
- List <Integer > temp = new ArrayList (curr );
47
- result .add (temp );
48
47
}
49
48
}
50
49
51
- public static void main (String ... args ) {
52
- _40 test = new _40 ();
53
- int [] candidates = new int []{10 , 1 , 2 , 7 , 6 , 1 , 5 };
54
- int target = 8 ;
55
- List <List <Integer >> result = test .combinationSum2 (candidates , target );
56
- CommonUtils .printListList (result );
57
- }
58
-
59
- }
50
+ }
0 commit comments