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

组合 #23

Open
Mooo-star opened this issue Jul 4, 2024 · 1 comment
Open

组合 #23

Mooo-star opened this issue Jul 4, 2024 · 1 comment
Labels
回溯 回溯算法 算法 记录算法

Comments

@Mooo-star
Copy link
Owner

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例 1:

输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

示例 2:

输入:n = 1, k = 1
输出:[[1]]

@Mooo-star Mooo-star added 回溯 回溯算法 算法 记录算法 labels Jul 4, 2024
@Mooo-star
Copy link
Owner Author

/**
 * @param {number} n
 * @param {number} k
 * @return {number[][]}
 */
var combine = function (n, k) {
    const result = []

    function backtrack(startIndex, path) {

        if (path.length === k) {
            result.push(path)
            return
        }

        for (let i = startIndex; i < n; i++) {
            backtrack(i + 1, [...path, i + 1])
        }

    }

    backtrack(0, [])

    return result
};

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