leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

216. 组合总和 III

Open buuing opened this issue 4 years ago • 0 comments

找出所有相加之和为 nk 个数的组合。组合中只允许含有 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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 回溯算法
const combinationSum3 = (k, n) => {
  const res = []
  const dfs = (set, target, prev) => {
    if (target === 0 && set.size === k) {
      res.push([...set])
    }
    for (let i = 1; i < 10; i++) {
      let next = target - i
      if (set.has(i) || i < prev) continue
      if (next < 0) break
      set.add(i)
      dfs(set, next, i)
      set.delete(i)
    }
  }
  dfs(new Set(), n, 0)
  return res
}

buuing avatar Jan 11 '21 12:01 buuing