Skip to content

77. Combinations

Problem

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4|1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

Example 2:

Input: n = 1, k = 1
Output: [[1|1]]
Explanation: There is 1 choose 1 = 1 total combination.

Constraints:

  • 1 <= n <= 20
  • 1 <= k <= n

Solve

Recursion

O(n!)

Solve any combine (n,k) using the “before” combine (n-1,k-1)

  • Introducing words array to keep the available words list we can use to create our combination
  • If any k == 1, we can safely return all member of remaining words lists
  • n should always large than
    class Solution:
        def combine(self, n: int, k: int, words = None) -> List[List[int]]:
            if words is None:
                words = [i for i in range(1,n+1)]
            if n < k:
                return [[|]]
            if n >= 1 and k == 1:
                return [[i] for i in words]
            result = []
            for i in range(len(words)):
                if n-1 >= len(words[i+1:]):
                    c = self.combine(n-1, k-1, words[i+1:])
                    for l in c:
                        result.append([words[i]]+l)
            return result
    

Optimized

Reuse path and Use number representation

O(n!)

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        words = n+1

        def helper(n, k, pos = 1, path = []):
            if n < k:
                return [[|]]
            if n >= 1 and k == 1:
                return [path + [i] for i in range(pos, words)]
            result = []
            for i in range(pos, words):
                if n >= words - i:
                    result += helper(n-1, k-1, i+1, path + [i])
                else:
                    break
            return result

        return helper(n,k)

Global path

O(n!)

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        words = n+1
        path = []
        def helper(level, pos = 1):
            if level == 1:
                return [path + [i] for i in range(pos, words)]
            result = []
            for i in range(pos, words-level+1):
                path.append(i)
                result += helper(level-1, i+1)
                path.pop()
            return result

        return helper(k)

Last update : September 17, 2023
Created : August 16, 2023