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> combine(int n, int k) {
        List> result = new ArrayList<>();
        List cur_res = new ArrayList<>();
        
        backtrack(n, k, 1, cur_res, result);
        return result;
    }

    private void backtrack(int n, int k, int start, List cur_res, List> 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);
        }
    }
}

你可能感兴趣的:(77. Combinations)