77. Combinations

Description

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],
]

Solution

DFS

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> combinations = new ArrayList<>();
        if (n < 1 || k < 1 || k > n) return combinations;
        
        List<Integer> combination = new ArrayList<>();
        combineRecur(1, n, k, combination, combinations);
        return combinations;
    }
    
    public void combineRecur(int begin, int end, int count
                             , List<Integer> combination
                             , List<List<Integer>> combinations) {
        if (count == 0) {
            combinations.add(new ArrayList<>(combination));
            return;
        }

        for (int i = begin; i <= Math.min(end, end + 1 - count); ++i) {
            combination.add(i);
            combineRecur(i + 1, end, count - 1, combination, combinations);
            combination.remove(combination.size() - 1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 昨天老公送了我两双我超级喜欢的鞋子,老公说就当作补情人节礼物。我挽着老公的胳膊说:咱可以每天都是情人节。老公说:算...
    周女阅读 193评论 0 0
  • 无论他(她)怎样,是凶恶善良,聪慧愚痴,美丽丑陋,傲慢谦卑,还是自私博爱,辛勤懒惰,顽劣正直……我们都要“爱”他(...
    菩提果zk张珂阅读 135评论 0 1
  • 是的,我撒谎了,撒了很多谎。 撒谎的原因因为胆怯,怕大人失望,因为虚荣。还有很多原因。 你现在一定知道,我都撒了哪...
    倾茶儿阅读 224评论 0 0
  • 今天早晨,在《枕边音乐》公众号里翻出了姚贝娜在《中国好声音》的参赛曲目《也许明天》。 由于自己很少关注流行音乐,之...
    一笑人生阅读 671评论 2 3