javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

77. 组合

Open Geekhyt opened this issue 4 years ago • 0 comments

原题链接

回溯

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

  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 avatar Feb 14 '21 05:02 Geekhyt