算法:组合问题

题目描述

给定两个整数 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;
        }
    }
相关推荐
Navigator_Z14 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
bbbb36514 小时前
图算法的最优路径搜索与边界约束建模的技术7
算法
東雪木14 小时前
编程算法学习——栈与队列算法
学习·算法·排序算法
CSDN_Colinw14 小时前
C++中的工厂方法模式
开发语言·c++·算法
liulilittle14 小时前
范围随机算法实现
开发语言·c++·算法·lua·c·js
2401_8579182915 小时前
C++中的访问者模式实战
开发语言·c++·算法
elseif12315 小时前
CSP-S提高级大纲
开发语言·数据结构·c++·笔记·算法·大纲·考纲
熊猫_豆豆15 小时前
Python 基于Dlib和OpenCV实现人脸融合算法+代码
图像处理·python·算法·人脸融合
Book思议-15 小时前
【数据结构实战】双向链表:在指定位置插入数据
c语言·数据结构·算法·链表
lightqjx15 小时前
【算法】前缀和
c++·算法·leetcode·前缀和