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

77. 组合 #33

Open
Geekhyt opened this issue Feb 14, 2021 · 0 comments
Open

77. 组合 #33

Geekhyt opened this issue Feb 14, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 14, 2021

原题链接

回溯

使用回溯法进行解题,在回溯的常规操作下注意以下两点:

  1. 每次递归当选满 k 个数时,将其推入最终集合。
  2. 回溯的过程中为了避免产生重复的组合,需要剪枝,通过指定下次递归的选择范围是 i + 1 来进行剪枝。
const combine = function(n, k) {
    const res = []
    const helper = function(start, cur) {
        if (cur.length === k) {
            res.push(cur.slice())
            return
        }
        for (let i = start; i <= n; i++) {
            cur.push(i)
            helper(i + 1, cur)
            cur.pop()
        }
    }
    helper(1, [])
    return res
}
@Geekhyt Geekhyt added the 中等 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant