[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(N!)
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()

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/11669393.html
今日推荐