1
- using System ;
2
- using System . Collections . Generic ;
3
- using System . Linq ;
1
+ public class Solution {
2
+ private List < IList < int > > ans = new List < IList < int > > ( ) ;
3
+ private List < int > t = new List < int > ( ) ;
4
+ private int [ ] candidates ;
4
5
5
- public class Solution
6
- {
7
- public IList < IList < int > > CombinationSum ( int [ ] candidates , int target )
8
- {
6
+ public IList < IList < int > > CombinationSum ( int [ ] candidates , int target ) {
9
7
Array . Sort ( candidates ) ;
10
- candidates = candidates . Distinct ( ) . ToArray ( ) ;
11
-
12
- var paths = new List < int > [ target + 1 ] ;
13
- paths [ 0 ] = new List < int > ( ) ;
14
- foreach ( var c in candidates )
15
- {
16
- for ( var j = c ; j <= target ; ++ j )
17
- {
18
- if ( paths [ j - c ] != null )
19
- {
20
- if ( paths [ j ] == null )
21
- {
22
- paths [ j ] = new List < int > ( ) ;
23
- }
24
- paths [ j ] . Add ( c ) ;
25
- }
26
- }
27
- }
28
-
29
- var results = new List < IList < int > > ( ) ;
30
- if ( paths [ target ] != null ) GenerateResults ( results , new Stack < int > ( ) , paths , target , paths [ target ] . Count - 1 ) ;
31
- return results ;
8
+ this . candidates = candidates ;
9
+ dfs ( 0 , target ) ;
10
+ return ans ;
32
11
}
33
12
34
- private void GenerateResults ( IList < IList < int > > results , Stack < int > result , List < int > [ ] paths , int remaining ,
35
- int maxIndex )
36
- {
37
- if ( remaining == 0 )
38
- {
39
- results . Add ( new List < int > ( result ) ) ;
13
+ private void dfs ( int i , int s ) {
14
+ if ( s == 0 ) {
15
+ ans . Add ( new List < int > ( t ) ) ;
40
16
return ;
41
17
}
42
- for ( var i = maxIndex ; i >= 0 ; -- i )
43
- {
44
- var value = paths [ remaining ] [ i ] ;
45
- result . Push ( value ) ;
46
- var nextMaxIndex = paths [ remaining - value ] . BinarySearch ( value ) ;
47
- if ( nextMaxIndex < 0 )
48
- {
49
- nextMaxIndex = ~ nextMaxIndex - 1 ;
50
- }
51
- GenerateResults ( results , result , paths , remaining - value , nextMaxIndex ) ;
52
- result . Pop ( ) ;
18
+ if ( i >= candidates . Length || s < candidates [ i ] ) {
19
+ return ;
53
20
}
21
+ dfs ( i + 1 , s ) ;
22
+ t . Add ( candidates [ i ] ) ;
23
+ dfs ( i , s - candidates [ i ] ) ;
24
+ t . RemoveAt ( t . Count - 1 ) ;
54
25
}
55
26
}
0 commit comments