前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-77-组合

LeetCode-77-组合

作者头像
benym
发布2022-07-14 16:38:42
3250
发布2022-07-14 16:38:42
举报
文章被收录于专栏:后端知识体系后端知识体系

# LeetCode-77-组合

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

示例1:

代码语言:javascript
复制
输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

# 解题思路

方法1、回溯:

典型的回溯题目,通过画一棵选择树不难看出,当有初始数组[1,2,3,4],k=2时

选择1之后,选择2,3,4能够组合成新的字串

选择2之后,选择3,4,能够组合成新的字串

可以归纳为,对于第i个选择的数,其和i+1开始到n的所有数进行组合,能够得到新的字串,且不会发生重复。

递归的终止条件为,k==2时,将字串添加进res中

当选择到达要求进行返回时,撤销上一次的选择,进行新的选择组合成新的字串

# Java代码

代码语言:javascript
复制
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(res, 1, n, k, new ArrayList<>());
        return res;
    }

    private void backtrack(List<List<Integer>> res, int i, int n, int k, ArrayList<Integer> temp) {
        if (k == temp.size()) {
            res.add(new ArrayList<>(temp));
            return;
        }
        for (int start = i; start < n + 1; start++) {
            temp.add(start);
            backtrack(res, start + 1, n, k, temp);
            temp.remove(temp.size() - 1);
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # LeetCode-77-组合
    • # 解题思路
      • # Java代码
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档