【陪伴式刷题】Day 21|回溯|77.组合(Combinations)

刷题顺序按照代码随想录建议

题目描述

英文版描述

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2 Output: \[1,2,1,3,1,4,2,3,2,4,3,4] Explanation: There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., 1,2 and 2,1 are considered to be the same combination.

Example 2:

Input: n = 1, k = 1 Output: \[1] Explanation: There is 1 choose 1 = 1 total combination.

Constraints:

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

英文版地址

leetcode.com/problems/co...

中文版描述

给定两个整数 nk,返回范围 [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.cn/problems/co...

解题方法

递归法

java 复制代码
class Solution {
List<Integer> temp = new ArrayList<Integer>();
    List<List<Integer>> ans = new ArrayList<List<Integer>>();

    public List<List<Integer>> combine(int n, int k) {
        dfs(1, n, k);
        return ans;
    }

    public void dfs(int cur, int n, int k) {
        // 剪枝:temp 长度加上区间 [cur, n] 的长度小于 k,不可能构造出长度为 k 的 temp
        if (temp.size() + (n - cur + 1) < k) {
            return;
        }
        // 记录合法的答案
        if (temp.size() == k) {
            ans.add(new ArrayList<Integer>(temp));
            return;
        }
        // 考虑选择当前位置
        temp.add(cur);
        dfs(cur + 1, n, k);
        temp.remove(temp.size() - 1);
        // 考虑不选择当前位置
        dfs(cur + 1, n, k);
    }
}

复杂度分析

  • 时间复杂度:
  • 空间复杂度:O(k)
相关推荐
zy happy24 分钟前
VMware虚拟机添加新的硬盘
java·linux·jvm·docker
AI人工智能+电脑小能手40 分钟前
【大白话说Java面试题 第192题】【08_Kafka篇】第8题:死信队列是什么?延时队列是什么?
java·kafka·消息队列·死信队列·延时队列
meng半颗糖42 分钟前
3.Java流程控制语句
java·开发语言·intellij-idea
大模型码小白1 小时前
企业级检索增强后端集成:Java 服务如何管理知识库版本
java·服务器·开发语言·人工智能·python·microsoft
用户6169182299931 小时前
记录一次死锁检测
java
jvmind_dev1 小时前
1c1g 容器莫名 OOM Killed?排查 Metaspace 持续增长与脚本引擎的坑
java·后端
AI多Agent协作实战派1 小时前
AI多Agent协作系统实战(二十二):从6列到12列——任务监控报告的进化之路
java·人工智能·uni-app·bug
用户3126874877201 小时前
@Transactional 注了等于没用?Spring 事务失效的 7 种场景,你踩过几个
java
千桐科技2 小时前
DataX 执行引擎正式加入:qData 开源版 v1.6.0 新增 Quartz + DataX 轻量运行模式!
java·大数据·开源·数据治理·数据中台·qdata
Irene19912 小时前
Oracle PL/SQL Developer 版本差异(11g、14)实战总结
java·开发语言