Skip to content

Commit 8193870

Browse files
authored
Update 0216.组合总和III.md
感觉这种解法更符合卡哥视频的讲解。
1 parent 3947eea commit 8193870

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

problems/0216.组合总和III.md

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -397,24 +397,31 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
397397
* @return {number[][]}
398398
*/
399399
var combinationSum3 = function(k, n) {
400-
const backtrack = (start) => {
401-
const l = path.length;
402-
if (l === k) {
403-
const sum = path.reduce((a, b) => a + b);
404-
if (sum === n) {
400+
let res = [];
401+
let path = [];
402+
let sum = 0;
403+
const dfs = (path,index) => {
404+
// 剪枝操作
405+
if (sum > n){
406+
return
407+
}
408+
if (path.length == k) {
409+
if(sum == n){
405410
res.push([...path]);
411+
return
406412
}
407-
return;
408413
}
409-
for (let i = start; i <= 9 - (k - l) + 1; i++) {
414+
for (let i = index; i <= 9 - (k-path.length) + 1;i++) {
410415
path.push(i);
411-
backtrack(i + 1);
412-
path.pop();
416+
sum = sum + i;
417+
index += 1;
418+
dfs(path,index);
419+
sum -= i
420+
path.pop()
413421
}
414422
}
415-
let res = [], path = [];
416-
backtrack(1);
417-
return res;
423+
dfs(path,1);
424+
return res
418425
};
419426
```
420427

0 commit comments

Comments
 (0)