算法:组合问题

题目描述

给定两个整数 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;
        }
    }
相关推荐
HXhlx3 小时前
CART决策树基本原理
算法·机器学习
Wect4 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱4 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
Gorway11 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风11 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect11 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
灵感__idea1 天前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
Wect1 天前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript
NAGNIP2 天前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
颜酱2 天前
单调栈:从模板到实战
javascript·后端·算法