↓Skip to main content
  1. LeetCode/

LeetCode 77: Combinations

·2 mins· ·
LeetCode Medium Backtracking
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-26

  • Submissions: Runtime Error ×3 → Accepted ×3

Approach
#

Combinations ignore order, so each choice starts after the previous one (Backtracking template): dfs(start, path) records path once it has length k. Prune when too few numbers remain: i only needs to reach n - (k - len(path)) + 1.

My Attempts
#

This took 6 submissions:

  • The first 2022-10-26 version called the helper without self. (NameError), and the helper itself returned the recursive call inside the for loop, exploring only the first branch; range(0, now[-1]) raised IndexError for an empty now.
  • A month later a rewrite requiring each next number to exceed the previous one passed.

Solution
#

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        def dfs(start, path):
            if len(path) == k:
                res.append(path[:])
                return
            for i in range(start, n - (k - len(path)) + 2):
                path.append(i)
                dfs(i + 1, path)
                path.pop()
        dfs(1, [])
        return res

Complexity
#

Time O(k · C(n, k)), space O(k) excluding output.

Mistakes to Avoid
#

  • Call a helper method through self., or nest it.
  • returning the recursive call inside the for loop explores only the first branch.
  • Record a copy, path[:].

Interview Explanation
#

Order does not matter, so I backtrack choosing each next number after the previous one, recording when k are chosen and pruning when too few numbers remain. Time O(k · C(n, k)).

Related

LeetCode 78: Subsets
·1 min
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 78 note: each element is either taken or not; iteratively, each new number copies every existing subset with the number appended
LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts
LeetCode 90: Subsets II
·2 mins
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 90 note: sort first; for a number equal to the previous one, extend only the subsets created in the previous step
LeetCode 47: Permutations II
·2 mins
LeetCode Medium Array Backtracking Sorting
LeetCode 47 note: sort first, and within a level skip a value equal to the previous one when the previous one is unused
LeetCode 39: Combination Sum
·2 mins
LeetCode Medium Array Backtracking
LeetCode 39 note: numbers may be reused, so the next level starts at i (not i + 1), which also avoids duplicates differing only in order
LeetCode 40: Combination Sum II
·2 mins
LeetCode Medium Array Backtracking
LeetCode 40 note: each number is used once and duplicates exist, so sort, start the next level at i + 1, and skip equal values within a level