算法:组合问题

题目描述

给定两个整数 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;
        }
    }
相关推荐
会编程的土豆21 分钟前
日常做题 vlog
数据结构·c++·算法
Omigeq1 小时前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
网络工程小王1 小时前
【大模型(LLM)的业务开发】学习笔记
人工智能·算法·机器学习
y = xⁿ1 小时前
【Leet Code 】滑动窗口
java·算法·leetcode
WBluuue1 小时前
数据结构与算法:二项式定理和二项式反演
c++·算法
nianniannnn1 小时前
力扣104.二叉树的最大深度 110. 平衡二叉树
算法·leetcode·深度优先
_深海凉_1 小时前
LeetCode热题100-只出现一次的数字
算法·leetcode·职场和发展
nianniannnn2 小时前
力扣206.反转链表 92.反转链表II
算法·leetcode·链表
澈2072 小时前
哈希表实战:从原理到手写实现
算法·哈希算法
旖-旎2 小时前
哈希表(存在重复元素||)(4)
数据结构·c++·算法·leetcode·哈希算法·散列表