玩命加载中 . . .

组合


描述

给定两个整数 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]]

提示:

1 <= n <= 20
1 <= k <= n

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

C++代码

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res; // 存放结果的二维数组
        vector<int> path; // 存放当前组合的一维数组
        dfs(n, k, 1, path, res); // 开始回溯
        return res;
    }

    // n: 给定的n,k: 给定的k,start: 从哪个数开始选,path: 当前组合的一维数组,res: 存放结果的二维数组
    void dfs(int n, int k, int start, vector<int>& path, vector<vector<int>>& res) {
        if(path.size() == k) { // 如果当前组合的长度等于k,说明找到了一个合法的组合
            res.push_back(path); // 将当前组合加入结果数组中
            return; // 回溯
        }
        for(int i = start; i <= n; i++) { // 枚举可选的数
            path.push_back(i); // 将当前数加入当前组合
            dfs(n, k, i + 1, path, res); // 从下一个数开始选,继续回溯
            path.pop_back(); // 回溯,将当前数从当前组合中移除
        }
    }
};

这里使用了一个辅助函数 dfs 来进行回溯,其中 start 参数表示从哪个数开始选。在每次递归中,我们枚举可选的数,将当前数加入当前组合,继续回溯,最后将当前数从当前组合中移除,回溯到上一层。当当前组合的长度等于k时,说明找到了一个合法的组合,将其加入结果数组中。

Python代码

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        path = []

        def dfs(start):
            if len(path) == k:
                res.append(path[:])
                return
            for i in range(start, n+1):
                path.append(i)
                dfs(i + 1)
                path.pop()

        dfs(1)
        return res

与 C++ 版本的思路一致,使用递归函数 dfs 进行回溯,其中 start 参数表示从哪个数开始选。在每次递归中,我们枚举可选的数,将当前数加入当前组合,继续回溯,最后将当前数从当前组合中移除,回溯到上一层。当当前组合的长度等于 k 时,说明找到了一个合法的组合,将其加入结果数组中。


文章作者: Jack Tim
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jack Tim !
评论
  目录