77. Combinations

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

public List<List<Integer>> combine(int n, int k) {
    ArrayList<List<Integer>> res = new ArrayList<>();
    if (n <= 0 || k > n) {
        return res;
    }
    helper(1, n, k, new ArrayList<Integer>(), res);
    return res;
}

private void helper(int currentVal, int limit, int count, ArrayList<Integer> path, ArrayList<List<Integer>> res) {
    if (count == 0) {
        res.add(new ArrayList<Integer>(path));
        return;
    }
    if (currentVal > limit) {
        return;
    }
    
    for (int i = currentVal; i <= limit; i++) {
        path.add(i);
        helper(i + 1, limit, count - 1, path, res);
        path.remove(path.size() - 1);
    }
}

时间复杂度为题解个数 n!/ (n - k)! / k!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,736评论 0 38
  • 新三板的市场定位是,以机构投资者和高净值人士为参与主体,为中小微企业提供融资,交易,并购。发债等功能的股票交易场所...
    云中鸟_d2b8阅读 890评论 0 0
  • 前面我们学习了三大财务报表:利润表、资产负债表、现金流量表,今天在此基础上,我们来讲一个财报中隐藏着的小秘密,手把...
    莉娜_lena阅读 5,993评论 6 9
  • 文/我心我愿秀 第一步:先扫墙。 第二步:擦柜子。 第三步:洗窗帘、沙发罩、衣服。 1、我家里有五个门,很多开关,...
    我心我愿秀阅读 2,767评论 0 3