[leedcode 77] Combinations

本文介绍了一个组合生成算法的实现过程,该算法能够根据输入的两个整数n和k,生成所有可能的k个数的组合,这些组合取自1到n的整数集合。文章通过一个具体的例子展示了算法的工作原理,并提供了完整的Java代码实现。

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

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
public class Solution {
    List<List<Integer>> res;
    List<Integer> seq;
    public List<List<Integer>> combine(int n, int k) {
        //注意分析题意,可选数组时从1到n,因此起始findCom函数的start参数需要从1开始
        res=new ArrayList<List<Integer>>();
        seq=new ArrayList<Integer>();
        findCom(n,1,0,k);
        return res;
    }
    public void findCom(int n,int start,int level,int k){
        if(level==k){
           res.add(new ArrayList<Integer>(seq)); 
           return;
        }
        for(int i=start;i<=n;i++){//注意i可以为n
            seq.add(i);
            findCom(n,i+1,level+1,k);
            seq.remove(seq.size()-1);
        }
    }
}

 

转载于:https://www.cnblogs.com/qiaomu/p/4646394.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值