LeetCode 77. 组合

系列文章目录

回溯算法组合相关习题:LeetCode 77. 组合



前言

  • 回溯算法之组合问题:N个数里面按一定规则找出k个数的集合

一、题目简介

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

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

示例一:

输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

示例二:

输入:n = 1, k = 1
输出:[[1]]

二、思想逻辑

  • 1、递归函数参数和返回值

result:存放符合条件结果的集合
pash:存放符合条件结果
stackIndex:记录下一层递归,搜索的起始位置
(一个集合来求组合的话,就需要startIndex)
(如果是多个集合取组合,各个集合之间相互不影响,那么就不用startIndex)

  • 2、确定终止条件

确定参数:像[1,2]、[2,3]这种组合可以理解成一维数组,所以需要一个集合LinkedList<Integer>存放这些组合。
将组合的每一个个体放入一个新的结果集,也就是二维数组List<List<Integer>>存放这些组合的结果集。

  • 3、确定单层递归逻辑

单层逻辑:stackIndex控制遍历的层数,当向pash集合中加入元素数量等同于k时,就将组合元素加入到result集合中。

在这里插入图片描述

完整代码

  • 实现一:
 class Solution {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> pash = new LinkedList<>();
    public List<List<Integer>> combine(int n, int k) {
        backtracking(n, k, 1);
        return result;

    }
    public void backtracking(int n, int k, int stackIndex){
        if(pash.size() == k){
            result.add(new ArrayList<>(pash));
            return ;
        }
        for(int i = stackIndex; i <= n; i++){
            pash.add(i);
            backtracking(n, k, i + 1);
            pash.removeLast();
        }
    }
}
  • 实现二:剪枝
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> pash = new LinkedList<>();
    public List<List<Integer>> combine(int n, int k) {
        backtracking(n, k, 1);
        return result;
    }
    public void backtracking(int n, int k, int stackIndex){
        if(pash.size() == k){
            result.add(new ArrayList<>(pash));
            return;
        }
        //剪枝
        for(int i = stackIndex; i <= n - (k - pash.size()) + 1; i++){
            pash.add(i);
            backtracking(n, k, i + 1);
            pash.removeLast();
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NumberTwoPlayer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值