77_ Combinations

[Medium][Backtracking]

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

Solution:

Idea:

  • For integer 1, there are two possibilities: the subset does not contain 1, or it does contain 1.

    • In the first case: we return all subsets of size k from 2 ... n

    • In the second case: we return all subsets of size k-1 from 2 ... n and append 1 to each of them

  • Use the same idea for each integer.

Time Complexity: O(n(nk))O(n\dbinom{n}{k}) from EPI book, hard to compute because of the two parameters

Space Complexity: O(k)O(k)

Last updated