Update 0216.组合总和III.md

感觉这种解法更符合卡哥视频的讲解。
This commit is contained in:
大眼睛图图
2022-10-16 20:34:22 +08:00
committed by GitHub
parent 3947eeaab9
commit 8193870813

View File

@ -397,24 +397,31 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
* @return {number[][]} * @return {number[][]}
*/ */
var combinationSum3 = function(k, n) { var combinationSum3 = function(k, n) {
const backtrack = (start) => { let res = [];
const l = path.length; let path = [];
if (l === k) { let sum = 0;
const sum = path.reduce((a, b) => a + b); const dfs = (path,index) => {
if (sum === n) { // 剪枝操作
res.push([...path]); if (sum > n){
} return
return;
} }
for (let i = start; i <= 9 - (k - l) + 1; i++) { if (path.length == k) {
if(sum == n){
res.push([...path]);
return
}
}
for (let i = index; i <= 9 - (k-path.length) + 1;i++) {
path.push(i); path.push(i);
backtrack(i + 1); sum = sum + i;
path.pop(); index += 1;
dfs(path,index);
sum -= i
path.pop()
} }
} }
let res = [], path = []; dfs(path,1);
backtrack(1); return res
return res;
}; };
``` ```