We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。 解集不能包含重复的组合。 示例 1:
输入: k = 3, n = 7 输出: [[1,2,4]] 示例 2: 输入: k = 3, n = 9 输出: [[1,2,6], [1,3,5], [2,3,4]]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combination-sum-iii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
简单的套前面几道递归回溯题的模板即可完成,注意剪枝条件,由于全部的值都是正整数,所以当和大于目标值的时候,但是数组长度还小于目标长度的话,可以直接 return。
/** * @param {number} k * @param {number} n * @return {number[][]} */ let combinationSum3 = function (k, n) { let res = [] let helper = (start, prevSum, prev) => { if (prev.length === k && prevSum === n) { res.push(prev) return } if (prevSum > n) { return } for (let i = start + 1; i <= 9; i++) { helper(i, prevSum + i, prev.concat(i)) } } helper(0, 0, []) return res }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。
解集不能包含重复的组合。
示例 1:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
简单的套前面几道递归回溯题的模板即可完成,注意剪枝条件,由于全部的值都是正整数,所以当和大于目标值的时候,但是数组长度还小于目标长度的话,可以直接 return。
The text was updated successfully, but these errors were encountered: