码迷,mamicode.com
首页 > 其他好文 > 详细

77. 组合

时间:2020-04-11 00:02:32      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:leetcode   integer   ati   tar   size   containe   set   ble   href   

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

示例:

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

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        // k个数
        List<List<Integer>> lists= new ArrayList<>();
        if(n < 1 || k > n || k < 1) return lists;
        
        help(n,k,1,new ArrayList<Integer>(),lists);
        return lists;
    }
    private void help(int n,int k,int index,List<Integer> list,List<List<Integer>> lists){
        // if(index == n + 1) return;
        if(list.size() == k){
            lists.add(new ArrayList<>(list));
            return;
        }
        for(int i = index;i <= n;i++){
            list.add(i);
            help(n,k,i + 1,list,lists);
            list.remove(list.size() - 1);
        }
    }
}

 

77. 组合

标签:leetcode   integer   ati   tar   size   containe   set   ble   href   

原文地址:https://www.cnblogs.com/zzytxl/p/12676929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!