leecode 第77题 组合(回溯)√

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_37719047/article/details/102721673

给定两个整数 n 和 k,返回 1 … n 中所有可能的 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) {
        List<List<Integer>>  ret=new ArrayList<List<Integer>>();
        List<Integer> list=new ArrayList<Integer>();
        combine(ret,list,1,n,k);
        return ret;
    }
    public void combine(List<List<Integer>>  ret, List<Integer> list,int start,int n,int k){
        if(list.size()==k){
            ret.add(new ArrayList(list));
            return;
        }
        for(int i=start;i<=n;i++){
            list.add(i);
            combine(ret,list,i+1,n,k);
            list.remove(list.size()-1);
        }
        return;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37719047/article/details/102721673
今日推荐