You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode 77组合问题解法的时间与空间复杂度分析咨询

LeetCode 77题「组合」解法的复杂度分析

题目描述

给定两个整数n和k,返回从范围[1,n]中选取k个数的所有可能组合,返回顺序不限。

实现代码

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        return combine(1, new LinkedList<>(), k, new ArrayList<>(), n);
    }

    private List<List<Integer>> combine(int start, LinkedList<Integer> comb, int k, List<List<Integer>> result, int n){
        if(k == 0){
            result.add(new LinkedList<>(comb));
            return result;
        }

        for(int i = start; i <= n-k+1; i++){
            comb.add(i);
            combine(i+1, comb, k-1, result, n);
            comb.pollLast();
        }
        return result;
    }
}

时间复杂度分析

该解法是回溯生成组合的典型实现:

  • 最终生成的有效组合总数为组合数C(n,k),即从n个元素中选k个的所有可能数量。
  • 每生成一个有效组合时,需要将当前的comb复制到结果集中,这个复制操作的时间复杂度是O(k)(每个组合包含k个元素)。
  • 递归过程中的元素添加、移除等操作均为O(1)的常数时间操作。

因此,整体时间复杂度为 O(k * C(n,k))。

空间复杂度分析

空间复杂度主要来自两部分:

  1. 递归调用栈:递归深度等于k,每次递归调用会将k减1,直到k=0终止,因此递归栈的空间复杂度为O(k)。
  2. 结果集存储:结果集中共有C(n,k)个组合,每个组合包含k个元素,这部分的空间复杂度为O(k * C(n,k))。
  3. 临时组合容器:当前正在构建的comb最多存储k个元素,空间复杂度为O(k),可被递归栈空间覆盖,无需额外计算。

综上,整体空间复杂度为 O(k * C(n,k))(结果集空间占主导地位)。

内容的提问来源于stack exchange,提问作者SherlockHolmesKePapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:50:19