leetcode 77. Combinations(java)

版权声明:未经博主同意,禁止转载,联系方式qq2928013321 https://blog.csdn.net/weixin_42130471/article/details/83094075

题目描述:

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

代码:

class Solution {
    public static List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(n<k||k==0)
            return res;
        res=combine(n-1,k-1);
        if(res.isEmpty())//n==k时才有可能为空
            res.add(new ArrayList<Integer>());
        for(List<Integer> list:res){
            list.add(n);
        }
        res.addAll(combine(n-1,k));
        return res;
    }
}

分析:

猜你喜欢

转载自blog.csdn.net/weixin_42130471/article/details/83094075
今日推荐