Dynamic Programming
20. Combination Sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.
You may return the combinations in any order.
- The same number may be chosen from
candidatesan unlimited number of times. - Two combinations are considered unique if the frequency of at least one chosen number is different.
- The test cases are generated such that the total number of unique combinations is less than 150.
Examples
Example 1
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 + 2 + 3 = 7 (number 2 can be reused)
7 = 7
These are the only valid combinations.
Example 2
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3
Input: candidates = [2], target = 1
Output: []
Constraints
1 <= candidates.length <= 302 <= candidates[i] <= 40- All elements of
candidatesare distinct 1 <= target <= 40
from typing import List
def dfs(i: int, candidates: List[int], target: int, cur: List[int], total: int, res: List[List[int]]) -> None:
if total == target:
res.append(cur.copy())
return
if i >= len(candidates) or total > target:
return
# Include the current candidate (it can be reused)
cur.append(candidates[i])
dfs(i, candidates, target, cur, total + candidates[i], res)
# Skip the current candidate and move to the next
cur.pop()
dfs(i + 1, candidates, target, cur, total, res)
candidates: List[int] = [2, 3]
target: int = 7
res: List[List[int]] = []
dfs(0, candidates, target, [], 0, res)
print(res) Keyboard shortcuts
← h Previous problem
→ l Next problem
Esc Back to index
? Toggle this help