55// Note:
66// All numbers (including target) will be positive integers.
77// 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:
1010// [
1111// [7],
1212// [2, 2, 3]
2424 */
2525var combinationSum = function ( candidates , target ) {
2626 var result = [ ] ;
27-
27+
2828 if ( candidates === null || candidates . length === 0 ) {
2929 return result ;
3030 }
31-
31+
3232 candidates . sort ( function ( a , b ) { return a > b ? 1 : - 1 } ) ;
33-
33+
3434 var output = [ ] ;
35-
35+
3636 generate ( candidates , result , output , target , 0 ) ;
37-
37+
3838 return result ;
3939} ;
4040
4141var generate = function ( candidates , result , output , sum , index ) {
4242 if ( sum === 0 ) {
43- result . push ( output . slice ( ) ) ;
43+ result . push ( output . slice ( ) ) ;
4444 }
4545 if ( sum < 0 ) {
4646 return ;
4747 }
48-
48+
4949 for ( var i = index ; i < candidates . length ; i ++ ) {
5050 if ( i > index && candidates [ i ] === candidates [ i - 1 ] ) {
5151 continue ;
5252 }
53-
53+
5454 if ( candidates [ i ] <= sum ) {
5555 output . push ( candidates [ i ] ) ;
5656 generate ( candidates , result , output , sum - candidates [ i ] , i ) ;
5757 output . pop ( ) ;
5858 }
5959 }
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