Combination Sum LeetCode
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 candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two 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: []
1. Approach (Idea)
-
Use Backtracking to explore all combinations.
-
At each step:
-
Pick a number and reduce
target
by that number. -
Reuse the same number (because allowed).
-
If
target == 0
, we found a valid combination — save it. -
If
target < 0
, stop (not a valid path).
-
-
Backtrack (undo last pick) and try next numbers.
Backtracking Function:
-
start
: current index in candidates. -
path
: current combination we're building. -
target
: remaining sum needed.
2. Dry Run (Example)
Input:
candidates = [2,3,6,7]
, target = 7
Step-by-Step:
Start with [] and target = 7
Pick 2 → path = [2], target = 5
Pick 2 again → path = [2,2], target = 3
Pick 2 again → path = [2,2,2], target = 1
Pick 2 again → path = [2,2,2,2], target = -1 (invalid, backtrack)
Pick 3 → path = [2,2,3], target = 0 (valid, save [2,2,3])
Try 6, target < 0 → backtrack
Try 7, target < 0 → backtrack
Pick 3 → path = [2,3], target = 2
Pick 3 again → path = [2,3,3], target = -1 → backtrack
Try 6, target < 0 → backtrack
Try 7, target < 0 → backtrack
Pick 6 → path = [2,6], target = -1 → backtrack
Pick 7 → path = [2,7], target = -2 → backtrack
Pick 3 → path = [3], target = 4
Pick 3 again → path = [3,3], target = 1
Pick 3 again → path = [3,3,3], target = -2 → backtrack
Pick 6 → path = [3,6], target = -2 → backtrack
Pick 7 → path = [3,7], target = -3 → backtrack
Pick 6 → path = [6], target = 1
Pick 6 again → path = [6,6], target = -5 → backtrack
Pick 7 → path = [6,7], target = -6 → backtrack
Pick 7 → path = [7], target = 0
Valid → save [7]
Final combinations = [[2,2,3], [7]]
3. Notes (Important Points)
✅ We can pick the same number multiple times → that's why backtrack(i, ...)
, not i+1
.
✅ If target == 0
→ valid combination → add a copy of path
into result
.
✅ If target < 0
→ stop exploring that path (invalid).
✅ Backtrack properly (after recursion call, remove last number from path).
✅ Candidates are distinct, so no need to worry about duplicates.
✅ Order of numbers inside combination does not matter.
Comments
Post a Comment