77. Combinations

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

总结见:http://www.jianshu.com/p/883fdda93a66

Solution:Backtracking(DFS)

思路:回溯法,类似深度优先进行组合,cur_result数组保持用当前尝试的结果,深度优先到底后(k==0)加入结果list,并step back (通过remove 当前cur_result的最后一位),换下一个尝试组合,后继续DFS重复此过程,实现上采用递归方式。
例:[12345]k=3: [123] [124] [125] [134] ...

Time Complexity: O(Cnk=n(n-1)(n-2)..(n-k+1)) ? (Not Sure)
Space Complexity(不算result的话): O(2n) : n是递归缓存的cur_result + n是缓存了n层的普通变量O(1) ? (Not Sure)

Solution Code:

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> cur_res = new ArrayList<>();
        
        backtrack(n, k, 1, cur_res, result);
        return result;
    }

    private void backtrack(int n, int k, int start, List<Integer> cur_res, List<List<Integer>> result) {
        if(k == 0) {
            result.add(new ArrayList<>(cur_res));
            return;
        }
        
        for(int i = start; i <= n; i++) {
            cur_res.add(i);
            backtrack(n, k - 1, i + 1, cur_res, result);
            cur_res.remove(cur_res.size() - 1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • Given two integers n and k, return all possible combinati...
    Jeanz阅读 400评论 0 0
  • LeetCode 77 Combinations Given two integers n and k, retu...
    ShuiLocked阅读 1,243评论 0 0
  • 淅淅沥沥的阳光落下 溅起一地时光的回响 任性的孩子 奔跑在路上 跑过清晰的地平线 跑过忧郁的海港 偶尔会停下 画一...
    莫自在阅读 192评论 3 2
  • 首先要明确一点,在减肥初期,尤其是大基数的减肥计划启动时,我不建议采用运动的方式,或者说是慎重选择运动方式。因为一...
    职心眼儿阅读 827评论 0 1