Featured image of post Combinations

Combinations

77. 组合

分析

  1. 初始化与递归入口
    • 定义 path 存储当前选择的组合,res 存储所有合法结果
    • 调用 dfs(n, k, 1) 开始递归。
  2. 递归终止条件
    • 若选满 k 个数(即 k == 0),将当前路径加入结果 res,并返回
  3. 递归过程
    • 遍历从 startn 的所有数:
      • 将当前数加入 path
      • 递归调用 dfs(n, k - 1, i + 1) 进入下一层搜索
      • 回溯时弹出当前数字,恢复状态

时间复杂度

总时间复杂度 O(C_n^k),组合数量为 C_n^k = n! / k!(n-k)!,每个组合需要遍历一次

空间复杂度

空间复杂度为 O(k)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution
{
public:
    std::vector<std::vector<int>> res;  // 存储结果
    std::vector<int> path;              // 当前路径

    vector<vector<int>> combine(int n, int k)
    {
        dfs(n, k, 1);  // 从数字 1 开始递归
        return res;
    }

    void dfs(int n, int k, int start)
    {
        // 递归终止条件:已选择 k 个数
        if (!k)
        {
            res.push_back(path);
            return;
        }

        for (int i = start; i <= n; ++i)
        {
            path.push_back(i);          // 选择当前数
            dfs(n, k - 1, i + 1);       // 递归搜索下一层
            path.pop_back();            // 回溯,撤销选择
        }
    }
};
Built with Hugo
Theme Stack designed by Jimmy