diff --git "a/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" "b/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" index ac28f9fcfa..d331726e55 100644 --- "a/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" +++ "b/problems/0216.\347\273\204\345\220\210\346\200\273\345\222\214III.md" @@ -417,6 +417,7 @@ func dfs(k, n int, start int, sum int) { ``` ### JavaScript +- 未剪枝: ```js /** @@ -424,32 +425,74 @@ func dfs(k, n int, start int, sum int) { * @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; }; ```