77. Combinations - Medium

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

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

 

use DFS (backtracking)

time = O(k * C(n, k)), space = O( C(n, k) )

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(n, k, 1, new ArrayList<>(), res);
        return res;
    }
    
    public void dfs(int n, int k, int start, List<Integer> list, List<List<Integer>> res) {
        if(list.size() == k) {
            res.add(new ArrayList<>(list));
            return;
        }
        
        for(int i = start; i <= n; i++) {
            list.add(i);
            dfs(n, k, i + 1, list, res);
            list.remove(list.size() - 1);
        }
    }
}

 

posted @ 2019-08-07 08:43  fatttcat  阅读(102)  评论(0编辑  收藏  举报