Question presented to candidate:
"Given a list of distinct positive integers candidates and a target, return every unique combination of candidates that sums to the target. Each number may be used any number of times. Code it in Python."
What a strong answer should cover:
- Backtracking with a running
remainingamount: choose a candidate, recurse withremaining - x, un-choose; record whenremainingis 0. - The start index: recurse with
i(reuse allowed) and never go back to smaller indices, so each combination appears once instead of in every order. - Pruning: sort the candidates and
breakas soon as a candidate exceedsremaining. - Complexity is exponential in target / smallest candidate; extra space is the recursion depth, at most target / smallest candidate.
- The variants: Combination Sum II (each number once, duplicates in input:
i + 1plus the skip rule) and counting combinations with coin-change DP. - Python details:
sorted()returns a new list (the input is left alone), recordpath[:], and the recursion depth is up to target / smallest candidate, which can reach the default limit of 1000 frames.
Clarifying questions expected:
- Are the candidates distinct and all positive?
- May a number be used more than once?
- Does the order of the combinations (or within a combination) matter?
Code / implementation expected: Yes โ a backtracking function in Python returning list[list[int]], with the start index and the sort-and-break pruning.