5
5
// Note:
6
6
// All numbers (including target) will be positive integers.
7
7
// The solution set must not contain duplicate combinations.
8
- // For example, given candidate set [2, 3, 6, 7] and target 7,
9
- // A solution set is:
8
+ // For example, given candidate set [2, 3, 6, 7] and target 7,
9
+ // A solution set is:
10
10
// [
11
11
// [7],
12
12
// [2, 2, 3]
24
24
*/
25
25
var combinationSum = function ( candidates , target ) {
26
26
var result = [ ] ;
27
-
27
+
28
28
if ( candidates === null || candidates . length === 0 ) {
29
29
return result ;
30
30
}
31
-
31
+
32
32
candidates . sort ( function ( a , b ) { return a > b ? 1 : - 1 } ) ;
33
-
33
+
34
34
var output = [ ] ;
35
-
35
+
36
36
generate ( candidates , result , output , target , 0 ) ;
37
-
37
+
38
38
return result ;
39
39
} ;
40
40
41
41
var generate = function ( candidates , result , output , sum , index ) {
42
42
if ( sum === 0 ) {
43
- result . push ( output . slice ( ) ) ;
43
+ result . push ( output . slice ( ) ) ;
44
44
}
45
45
if ( sum < 0 ) {
46
46
return ;
47
47
}
48
-
48
+
49
49
for ( var i = index ; i < candidates . length ; i ++ ) {
50
50
if ( i > index && candidates [ i ] === candidates [ i - 1 ] ) {
51
51
continue ;
52
52
}
53
-
53
+
54
54
if ( candidates [ i ] <= sum ) {
55
55
output . push ( candidates [ i ] ) ;
56
56
generate ( candidates , result , output , sum - candidates [ i ] , i ) ;
57
57
output . pop ( ) ;
58
58
}
59
59
}
60
- }
60
+ }
61
+
62
+
63
+ // Another solution
64
+ var combinationSum = function ( candidates , target ) {
65
+ var results = [ ] ;
66
+ comb ( candidates . sort ( ) , 0 , [ ] , 0 , target , results ) ;
67
+ return results ;
68
+ } ;
69
+
70
+ var comb = function ( cand , index , partial , partialSum , target , results ) {
71
+ if ( target === partialSum ) {
72
+ results . push ( partial ) ;
73
+ return ;
74
+ }
75
+ if ( cand . length === index || partialSum > target ) {
76
+ return ;
77
+ }
78
+
79
+ comb ( cand , index + 1 , partial , partialSum , target , results ) ;
80
+ comb ( cand , index , partial . concat ( [ cand [ index ] ] . concat ( [ cand [ index ] ] ) ) ,
81
+ partialSum + 2 * cand [ index ] , target , results ) ;
82
+ comb ( cand , index + 1 , partial . concat ( [ cand [ index ] ] ) ,
83
+ partialSum + cand [ index ] , target , results ) ;
84
+ } ;
0 commit comments