refactor: 0077.组合.md

This commit is contained in:
qiufeihong2018
2024-05-01 19:10:32 +08:00
parent 3e5c1705c2
commit d1d7cdeecd

View File

@ -499,24 +499,28 @@ var combine = function (n, k) {
剪枝: 剪枝:
```javascript ```javascript
let result = [] var combine = function (n, k) {
let path = [] // 回溯法
var combine = function(n, k) { let result = [],
result = [] path = [];
combineHelper(n, k, 1) let backtracking = (_n, _k, startIndex) => {
return result // 终止条件
if (path.length === _k) {
result.push(path.slice());
return;
}
// 循环本层集合元素
for (let i = startIndex; i <= _n - (_k - path.length) + 1; i++) {
path.push(i);
// 递归
backtracking(_n, _k, i + 1);
// 回溯操作
path.pop();
}
};
backtracking(n, k, 1);
return result;
}; };
const combineHelper = (n, k, startIndex) => {
if (path.length === k) {
result.push([...path])
return
}
for (let i = startIndex; i <= n - (k - path.length) + 1; ++i) {
path.push(i)
combineHelper(n, k, i + 1)
path.pop()
}
}
``` ```
### TypeScript ### TypeScript