Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2c45fdd

Browse files
Merge pull requestchihungyu1116#2 from ignacio-chiazzo/combination-sum
combination Sum DFS Solution
2 parentsbd0c05b +a05d4ec commit2c45fdd

File tree

1 file changed

+35
-11
lines changed

1 file changed

+35
-11
lines changed

‎39 Combination Sum.js

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
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]
@@ -24,37 +24,61 @@
2424
*/
2525
varcombinationSum=function(candidates,target){
2626
varresult=[];
27-
27+
2828
if(candidates===null||candidates.length===0){
2929
returnresult;
3030
}
31-
31+
3232
candidates.sort(function(a,b){returna>b ?1 :-1});
33-
33+
3434
varoutput=[];
35-
35+
3636
generate(candidates,result,output,target,0);
37-
37+
3838
returnresult;
3939
};
4040

4141
vargenerate=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(vari=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+
varcombinationSum=function(candidates,target){
65+
varresults=[];
66+
comb(candidates.sort(),0,[],0,target,results);
67+
returnresults;
68+
};
69+
70+
varcomb=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

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp