一、解题思路
这道题除了限定数组的元素以及组成序列所需元素的个数条件之外,本质上与40. Combination Sum II的解法一致:
二、代码实现
const combinationSum3 = (k, n) => {
const candidates = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const ans = []
const dfs = (currentIndex, currentArray, amount, sum) => {
if (sum === 0 && amount === k) {
ans.push(currentArray.slice())
return
}
if (sum < 0 || amount > k) {
return
}
for (let i = currentIndex; i < 9; i++) {
const item = candidates[i]
currentArray.push(item)
dfs(i + 1, currentArray, amount + 1, sum - item)
currentArray.pop()
}
}
dfs(0, [], 0, n)
return ans
}
如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。

您还可以在这些地方找到我: