1
1
package _39 ;
2
2
3
3
import java .util .ArrayList ;
4
- import java .util .Arrays ;
5
4
import java .util .List ;
6
5
7
6
class Solution {
8
7
public List <List <Integer >> combinationSum (int [] candidates , int target ) {
9
- Arrays .sort (candidates );
10
- return find (candidates , target , 0 );
8
+ if (candidates == null || candidates .length == 0 )
9
+ return new ArrayList <>();
10
+
11
+ List <List <Integer >> result = new ArrayList <>();
12
+
13
+ helper (candidates , target , 0 , new ArrayList <>(), result );
14
+
15
+ return result ;
11
16
}
12
17
13
- public List < List < Integer >> find (int [] candidates , int target , int start ) {
14
- if (target <= 0 )
15
- return new ArrayList <>() ;
18
+ private void helper (int [] candidates , int target , int start , List < Integer > tmp , List < List < Integer >> result ) {
19
+ if (target < 0 )
20
+ return ;
16
21
17
- List <List <Integer >> results = new ArrayList <>();
18
- for (int i = start ; i < candidates .length ; i ++) {
19
- if (target - candidates [i ] == 0 ) {
20
- List <Integer > list = new ArrayList <>();
21
- list .add (candidates [i ]);
22
- results .add (list );
23
- return results ;
24
- }
25
-
26
- List <List <Integer >> lists = find (candidates , target - candidates [i ], i );
27
- for (List <Integer > list : lists ) {
28
- list .add (candidates [i ]);
29
- results .add (list );
30
- }
22
+ if (target == 0 ) {
23
+ result .add (tmp );
24
+ return ;
31
25
}
32
26
33
- return results ;
27
+ if (start >= candidates .length )
28
+ return ;
29
+
30
+ helper (candidates , target , start + 1 , tmp , result );
31
+
32
+ List <Integer > list = new ArrayList <>(tmp );
33
+ list .add (candidates [start ]);
34
+ helper (candidates , target - candidates [start ], start , list , result );
34
35
}
35
36
36
37
public static void main (String [] args ) {
38
+ System .out .println (new Solution ().combinationSum (new int []{2 , 3 , 5 }, 8 ));
37
39
System .out .println (new Solution ().combinationSum (new int []{2 , 3 , 6 , 7 }, 7 ));
38
40
}
39
- }
41
+ }
0 commit comments