mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0216.组合总和III.md
感觉这种解法更符合卡哥视频的讲解。
This commit is contained in:
@ -397,24 +397,31 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
|
||||
* @return {number[][]}
|
||||
*/
|
||||
var combinationSum3 = function(k, n) {
|
||||
const backtrack = (start) => {
|
||||
const l = path.length;
|
||||
if (l === k) {
|
||||
const sum = path.reduce((a, b) => a + b);
|
||||
if (sum === n) {
|
||||
res.push([...path]);
|
||||
}
|
||||
return;
|
||||
let res = [];
|
||||
let path = [];
|
||||
let sum = 0;
|
||||
const dfs = (path,index) => {
|
||||
// 剪枝操作
|
||||
if (sum > n){
|
||||
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);
|
||||
backtrack(i + 1);
|
||||
path.pop();
|
||||
sum = sum + i;
|
||||
index += 1;
|
||||
dfs(path,index);
|
||||
sum -= i
|
||||
path.pop()
|
||||
}
|
||||
}
|
||||
let res = [], path = [];
|
||||
backtrack(1);
|
||||
return res;
|
||||
dfs(path,1);
|
||||
return res
|
||||
};
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user