Skip to content
New issue

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

组合总和 III-216 #74

Open
sl1673495 opened this issue Jun 12, 2020 · 0 comments
Open

组合总和 III-216 #74

sl1673495 opened this issue Jun 12, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

找出所有相加之和为  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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant