[LC] 77. Combinations

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

Example:

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

Time: O(C(N, k))
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        start = 0
        my_list = []
        self.dfs(n, k, 1, my_list, res)
        return res

    def dfs(self, n, k, start, my_list, res):
        if k == 0:
            res.append(list(my_list))
            return
        for i in range(start, n + 1):
            my_list.append(i)
            # need to use i + 1 instead of start + 1 for the next level
            self.dfs(n, k - 1, i + 1, my_list, res)
            my_list.pop()
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        helper(res, new ArrayList<Integer>(), n, k, 1);
        return res;
    }
    
    private void helper(List<List<Integer>> res, List<Integer> list, int n, int k, int start) {
        if (k == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        // need to go deeper based on current i and ignore the previous result, so that use i + 1
        for (int i = start; i <= n; i++) {
            list.add(i);
            helper(res, list, n, k - 1, i + 1);
            list.remove(list.size() - 1);
        }
    }
}
原文地址:https://www.cnblogs.com/xuanlu/p/11669393.html