Skip to content

Commit

Permalink
refactor: 0216.组合总和III.md
Browse files Browse the repository at this point in the history
  • Loading branch information
qiufeihong2018 committed May 1, 2024
1 parent d1d7cde commit 5e6a657
Showing 1 changed file with 68 additions and 25 deletions.
93 changes: 68 additions & 25 deletions problems/0216.组合总和III.md
Original file line number Diff line number Diff line change
Expand Up @@ -417,39 +417,82 @@ func dfs(k, n int, start int, sum int) {
```

### JavaScript
- 未剪枝:

```js
/**
* @param {number} k
* @param {number} n
* @return {number[][]}
*/
var combinationSum3 = function(k, n) {
let res = [];
let path = [];
let sum = 0;
const dfs = (path,index) => {
// 剪枝操作
if (sum > n){
return
}
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);
sum = sum + i;
index += 1;
dfs(path,index);
sum -= i
path.pop()
}
var combinationSum3 = function (k, n) {
// 回溯法
let result = [],
path = [];
const backtracking = (_k, targetSum, sum, startIndex) => {
// 终止条件
if (path.length === _k) {
if (sum === targetSum) {
result.push(path.slice());
}
// 如果总和不相等,就直接返回
return;
}
dfs(path,1);
return res

// 循环当前节点,因为只使用数字1到9,所以最大是9
for (let i = startIndex; i <= 9; i++) {
path.push(i);
sum += i;
// 回调函数
backtracking(_k, targetSum, sum, i + 1);
// 回溯
sum -= i;
path.pop();
}
};
backtracking(k, n, 0, 1);
return result;
};
```

- 剪枝:

```js
/**
* @param {number} k
* @param {number} n
* @return {number[][]}
*/
var combinationSum3 = function (k, n) {
// 回溯法
let result = [],
path = [];
const backtracking = (_k, targetSum, sum, startIndex) => {
if (sum > targetSum) {
return;
}
// 终止条件
if (path.length === _k) {
if (sum === targetSum) {
result.push(path.slice());
}
// 如果总和不相等,就直接返回
return;
}

// 循环当前节点,因为只使用数字1到9,所以最大是9
for (let i = startIndex; i <= 9 - (_k - path.length) + 1; i++) {
path.push(i);
sum += i;
// 回调函数
backtracking(_k, targetSum, sum, i + 1);
// 回溯
sum -= i;
path.pop();
}
};
backtracking(k, n, 0, 1);
return result;
};
```

Expand Down

0 comments on commit 5e6a657

Please sign in to comment.