class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res, sol = [], [] n = len(candidates) def backtrack(i, cur_sum): # 1. index out of range and sum > target if i == n or cur_sum > target: return # 2. we actually get the target if cur_sum == target: res.append(sol[:]) return backtrack(i + 1, cur_sum) # use the same value sol.append(candidates[i]) backtrack(i, cur_sum + candidates[i]) sol.pop() backtrack(0, 0) return res
Explanation
It’s similar to Subsets but we can use duplicates. We’ll have a backtrack function that takes an index, i and and sum, cur_sum
Base cases:
We achieve the target
append to res and return
Index is out of range or the current sum > target
just return
Left: this path means we keep using the same num at i. so just increment i
Right: this is a little more involved.
We’ll add the current num at i to sol
We’ll call backtrack on i and the current sum + the num at i.