#77

Combinations

Medium
BacktrackingBacktrackingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n choose k)
O(n choose k)
Space
O(k)
O(k)
💡

Intuition

Time O(n choose k)Space O(k)

The optimal solution uses backtracking to build combinations incrementally. This avoids generating all combinations upfront and only constructs valid combinations, making it more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a result list to store combinations.
  2. 2Step 2: Use a recursive function to build combinations by adding numbers from the current start index.
  3. 3Step 3: If the current combination reaches size k, add it to the result.
  4. 4Step 4: Backtrack by removing the last added number and continue exploring.
solution.py15 lines
1# Full working Python code
2from typing import List
3
4def combine(n: int, k: int) -> List[List[int]]:
5    result = []
6    def backtrack(start, path):
7        if len(path) == k:
8            result.append(path[:])
9            return
10        for i in range(start, n + 1):
11            path.append(i)
12            backtrack(i + 1, path)
13            path.pop()
14    backtrack(1, [])
15    return result

Complexity note: The time complexity remains O(n choose k) since we still explore combinations, but we do it more efficiently. The space complexity is O(k) for storing the current combination.

  • 1Understanding backtracking is crucial for solving combination problems efficiently.
  • 2Recognizing that combinations are unordered helps in avoiding duplicates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.