【陪伴式刷题】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)
相关推荐
wuqingshun3141597 分钟前
大致说一下程序、进程、线程
java·运维·服务器·开发语言
wuqingshun3141599 分钟前
Object有哪些方法,大致说一下每个方法的含义?
java·开发语言·jvm
Coder_Boy_11 分钟前
Java高级_资深_架构岗 核心知识点(模块三:高并发)
java·spring boot·分布式·面试·架构
Tisfy11 分钟前
LeetCode 762.二进制表示中质数个计算置位:位运算(mask O(1)判断)
算法·leetcode·题解·位运算·质数
Coder_Boy_20 分钟前
Java高级_资深_架构岗 核心知识点全解析(模块二:Spring生态 架构岗必备)
java·spring boot·spring·架构
追随者永远是胜利者40 分钟前
(LeetCode-Hot100)215. 数组中的第K个最大元素
java·算法·leetcode·职场和发展·go
晔子yy41 分钟前
ReAct范式全流程详解
java·ai·react
渣瓦攻城狮43 分钟前
互联网大厂Java面试实战:核心技术与场景分析
java·大数据·redis·spring·微服务·面试·技术分享
We་ct44 分钟前
LeetCode 112. 路径总和:两种解法详解
前端·算法·leetcode·typescript
wuqingshun3141591 小时前
说一下JVM内存结构
java·开发语言·jvm