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,39 +23,27 @@ All numbers (including target) will be positive integers.
25
23
]*/
26
24
public class _39 {
27
25
28
- public List <List <Integer >> combinationSum (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 >> combinationSum (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
- private void backtracking (int [] candidates , int target , int startIndex , List <Integer > curr , List <List <Integer >> result ) {
36
- if (target > 0 ) {
37
- int prev = - 1 ;
38
- for ( int i = startIndex ; i < candidates . length ; i ++ ) {
39
- if ( candidates [ i ] > target ) {
40
- return ; //this is one very important step to optimize this algorithm: pruning
41
- }
42
- if ( prev != - 1 && prev == candidates [i ]) {
43
- continue ;
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 ; i ++) {
37
+ if ( candidates [ i ] > target ) {
38
+ return ; //pruning
39
+ }
40
+ curr . add ( candidates [ i ]);
41
+ backtracking ( candidates , target - candidates [i ], i , curr , result );
42
+ curr . remove ( curr . size () - 1 ) ;
44
43
}
45
- curr .add (candidates [i ]);
46
- backtracking (candidates , target - candidates [i ], i , curr , result );
47
- curr .remove (curr .size () - 1 );
44
+ } else if (target == 0 ) {
45
+ result .add (new ArrayList (curr ));
48
46
}
49
- } else if (target == 0 ) {
50
- result .add (new ArrayList (curr ));
51
47
}
52
48
}
53
-
54
-
55
- public static void main (String ... args ) {
56
- _39 test = new _39 ();
57
- int [] candidates = new int []{2 , 3 , 6 , 7 };
58
- int target = 7 ;
59
- List <List <Integer >> result = test .combinationSum (candidates , target );
60
- CommonUtils .printListList (result );
61
- }
62
-
63
49
}
0 commit comments