算法:组合问题

题目描述

给定两个整数 n 和 k,返回范围 1, n 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例:

输入:n = 4, k = 2

输出:

\[2,4,

3,4,

2,3,

1,2,

1,3,

1,4\],

函数:

java 复制代码
public List<List<Integer>> combine(int n, int k) {

}

思路

经典回溯问题,我的针对回溯问题解题思路如下:

首先写出for循环形式的逻辑代码(不要求代码上可行,主要理清楚逻辑):

java 复制代码
public List<List<Integer>> res;

public List<List<Integer>> combine(int n, int k) {
	for(int i=1;i<=n;i++)
		for(int j=i+1;j<=n;j++)
			for(int l=j+1;l<=n;l++)
				for(....)
					...(总共应有k个for循环)
					{
						res.add(new ArrayList<>(){i,j,l,m,o,p,.....} //共k个
					}
	return res;
}
  • 需要k个for循环,数量可变因此要使用递归来模拟这个"可变数量的for循环",而递归的每一层都有一个for循环

  • 通过观察可见,除了第一层初始i=1,从第二层开始,初始值都为上一层的值+1,如j=i+1,l=j+1。因此我们可以知道递归的for循环条件必然是:

    java 复制代码
    for(int i=index;i<=n;i++)

    而进入下一层递归传入的index参数必然是i+1。那么代码结构就确定了,剩下的就好写了。

  • 完整代码(不带剪枝):

    java 复制代码
    class Solution {
        public List<Integer> path = new ArrayList<>();
        public List<List<Integer>> res = new ArrayList<>();
    
        public void combineHelper(int index, int n, int k){
            if(index>n) return;
            for(int i=index;i<=n;i++){
                path.add(i);
                if(path.size()==k){
                    res.add(new ArrayList<>(path)); //收割结果
                }else{
                    combineHelper(i+1,n,k); //进入下一层递归,初始index值应为上一层i值+1
                }
                path.remove(path.size()-1); //pop操作,模拟多层for循环
            }
            return;
        }
    
        public List<List<Integer>> combine(int n, int k) {
            combineHelper(1,n,k);
            return res;
        }
    }
  • 带上剪枝的话,就是

    java 复制代码
    class Solution {
        public List<Integer> path = new ArrayList<>();
        public List<List<Integer>> res = new ArrayList<>();
    
        public void combineHelper(int index, int n, int k){
            // if(index>n) return;
            if(path.size()+n-index+1<k) return; //多了这一行,当剩下所有值都加到path里,长度还是达不到k,就可以提前返回了。
            for(int i=index;i<=n;i++){
                path.add(i);
                if(path.size()==k){
                    res.add(new ArrayList<>(path));
                }else{
                    combineHelper(i+1,n,k);
                }
                path.remove(path.size()-1);
            }
            return;
        }
    
        public List<List<Integer>> combine(int n, int k) {
            combineHelper(1,n,k);
            return res;
        }
    }
相关推荐
怕浪猫14 分钟前
用了两年 AI 编程工具后,我重新理解了什么是「资深工程师」
算法·面试·架构
hetao173383739 分钟前
2026-08-27~29 hetao1733837 的刷题记录
c++·算法
云淡风轻~窗明几净1 小时前
宇宙管理学猜想
算法·图论
春风解人意1 小时前
从零开始学习嵌入式P28----线程
c语言·学习·算法
luj_17681 小时前
合法避税与投资评估实战指南
c语言·开发语言·网络·经验分享·算法
ychqsq1 小时前
144.扎根
经验分享·职场和发展
Bruce_Liuxiaowei2 小时前
驴滑块拼图游戏:从19世纪的纸片谜题到数学博弈论
人工智能·算法
一直C2 小时前
Linux系统编程|信号进阶 + SystemV IPC(消息队列、共享内存)
linux·c语言·开发语言·算法·青少年编程·vim
鹿角片ljp3 小时前
LeetCode 141. 环形链表|从 HashSet 到快慢指针 O (1) 空间最优解
算法·leetcode·链表
薛定e的猫咪3 小时前
(NeurIPS 2022)GraphGPS:MPNN 与全局注意力的融合之道
人工智能·深度学习·学习·算法