【陪伴式刷题】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...

中文版描述

给定两个整数 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.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)
相关推荐
郑州光合科技余经理几秒前
出海外卖平台:支付对接为什么要和下单收款分开
android·java·开发语言·前端·后端·php·ai编程
我是人✓6 分钟前
Spring框架的事务管理
java·后端·spring
javachen__20 分钟前
JsonView:一套VO实现多角色字段返回
java·linux·服务器
行者-全栈开发36 分钟前
SpringBoot 生产环境踩坑实录:10个真实故障案例与教训
java·spring boot·后端
李福春39 分钟前
斗破Google ADK Java苍穹-第7境斗皇-御天地-Harness治理
java·人工智能·python·深圳同盟·腾讯云架构师技术同盟·adk java·harness 治理
Wang's Blog41 分钟前
Java 项目部署之 Docker工具快速入门: 容器命令练习:创建、改文件、重启到删除的完整闭环
java·开发语言·docker
我是人✓41 分钟前
Java面向对象核心特性深度解析
java·前端·算法
Wx-bishekaifayuan1 小时前
springboot线上中医药养生平台管理系统36753-计算机课程设计、毕业设计
java·spring boot·后端·spring·课程设计·express·旅游
Wx-bishekaifayuan1 小时前
springboot大学生就业平台47691-计算机课程设计、毕业设计
java·spring boot·后端·elasticsearch·课程设计·express·旅游
汤姆yu1 小时前
基于springboot+vue的企业OA办公系统
java·spring boot·后端·oa办公