↓Skip to main content
  1. LeetCode/

LeetCode 216: Combination Sum III

·1 min· ·
LeetCode Medium Array 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-11-12

  • Submissions: Wrong Answer → Accepted ×2

Approach
#

The same combination backtracking as LC 77 (Backtracking template) with candidates fixed to 1 through 9, the next level starting at i + 1. Prune when the count exceeds k or the sum exceeds n.

My Attempts
#

Attempt 1 drew candidates from range(min_number + 1, n + 1), 1 to n instead of 1 to 9: k = 3, n = 24 returned combinations like [1, 2, 21]. Restricting to 1 through 9 passed.

Solution
#

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res = []
        def dfs(start, remain, path):
            if len(path) == k:
                if remain == 0:
                    res.append(path[:])
                return
            for x in range(start, 10):
                if x > remain:
                    break
                path.append(x)
                dfs(x + 1, remain - x, path)
                path.pop()
        dfs(1, n, [])
        return res

Complexity
#

Time O(C(9, k) · k), space O(k).

Mistakes to Avoid
#

  • Candidates are 1 to 9 only, not 1 to n.

Interview Explanation
#

With candidates 1 to 9 each used once, I backtrack combinations starting each level above the current number, check the sum once k are chosen, and prune overshoots.

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