算法:组合问题

题目描述

给定两个整数 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;
        }
    }
相关推荐
hh随便起个名3 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
写写闲篇儿3 小时前
微软面试之白板做题
面试·职场和发展
Dingdangcat864 小时前
城市交通多目标检测系统:YOLO11-MAN-FasterCGLU算法优化与实战应用_3
算法·目标检测·目标跟踪
tang&5 小时前
滑动窗口:双指针的优雅舞步,征服连续区间问题的利器
数据结构·算法·哈希算法·滑动窗口
拼命鼠鼠5 小时前
【算法】矩阵链乘法的动态规划算法
算法·矩阵·动态规划
LYFlied5 小时前
【每日算法】LeetCode 17. 电话号码的字母组合
前端·算法·leetcode·面试·职场和发展
式5166 小时前
线性代数(八)非齐次方程组的解的结构
线性代数·算法·机器学习
橘颂TA6 小时前
【剑斩OFFER】算法的暴力美学——翻转对
算法·排序算法·结构与算法
叠叠乐6 小时前
robot_state_publisher 参数
java·前端·算法
hweiyu007 小时前
排序算法:冒泡排序
算法·排序算法