前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布

组合

作者头像
名字是乱打的
发布2021-12-22 16:10:26
6300
发布2021-12-22 16:10:26
举报
文章被收录于专栏:软件工程软件工程

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

示例:

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

代码:
代码语言:javascript
复制
class Solution {
    
   private List<List<Integer>> res;

        public List<List<Integer>> combine(int n, int k) {

            res = new ArrayList<List<Integer>>();
            if (n<1 || k<1 || n<k) {
                return res;
            }
            List<Integer> selected = new ArrayList<Integer>();
            pickNext(1, n, k, selected);
            return res;
        }

        public void pickNext(int min, int max, int k, List<Integer> selected) {

            if (k==0) {
                res.add(new ArrayList<Integer>(selected));
                return;
            }

            for (int i=min; i<=max-k+1; i++) {
                selected.add(i);
                pickNext(i+1, max, k-1, selected);
                selected.remove(selected.size()-1);
            }
        }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/3/26 下,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
    • 代码:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档