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

Solution: DFS

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        combinations = []
        combination = []

        def dfs(start, k):
            if n - start + 1 < k:
                return
            if k <= 0:
                combinations.append(list(combination))
                return
            for num in xrange(start, n + 1):
                combination.append(num)
                dfs(num + 1, k - 1)
                combination.pop()

        dfs(1, k)
        return combinations

results matching ""

    No results matching ""