Skip to content

77. 组合 #33

@Geekhyt

Description

@Geekhyt

原题链接

回溯

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

  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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy