Combination Sum - Problem
The Combination Sum Challenge: Imagine you're a treasure hunter with a magical bag of coins of different denominations, and you need to find all possible ways to make exact change for a target amount. Here's the twist - your bag has unlimited coins of each denomination!
Given an array of
Key Rules:
Given an array of
candidates containing distinct positive integers and a target integer, your mission is to return all unique combinations of candidates where the chosen numbers sum to the target.Key Rules:
- ๐ You can use the same number multiple times
- ๐ฏ Each combination must sum exactly to the target
- โจ Return combinations in any order
- ๐ข Two combinations are unique if they differ in frequency of at least one number
[2,3,6,7] and target 7, you could make 7 using [7] or [2,2,3] - both are valid! Input & Output
example_1.py โ Basic Case
$
Input:
candidates = [2,3,6,7], target = 7
โบ
Output:
[[2,2,3],[7]]
๐ก Note:
We can make 7 in two ways: using three coins [2,2,3] (2+2+3=7) or one coin [7]. Both combinations are unique and sum to the target.
example_2.py โ Multiple Solutions
$
Input:
candidates = [2,3,5], target = 8
โบ
Output:
[[2,2,2,2],[2,3,3],[3,5]]
๐ก Note:
Three different ways to make 8: four 2's (2+2+2+2=8), two 2's and two 3's (2+3+3=8), or one 3 and one 5 (3+5=8).
example_3.py โ No Solution
$
Input:
candidates = [2], target = 1
โบ
Output:
[]
๐ก Note:
Cannot make target 1 using only candidate 2, since 2 > 1. No valid combinations exist.
Visualization
Tap to expand
Understanding the Visualization
1
Sort Your Coins
Arrange coins [2,3,6,7] in order so we can stop early when a coin is too big
2
Start Exploring
Begin with empty combination, try each coin type systematically
3
Smart Recursion
When using a coin, we can use it again (unlimited supply) or try larger coins
4
Early Stopping
If current coin > remaining target, skip it and all larger coins
5
Collect Solutions
When remaining target = 0, we found a valid combination!
Key Takeaway
๐ฏ Key Insight: Backtracking systematically explores the solution space while pruning impossible branches early, making it the perfect algorithm for finding all valid combinations efficiently.
Time & Space Complexity
Time Complexity
O(N^(T/M))
Same worst case as brute force, but with significant practical improvements due to pruning
โ Linear Growth
Space Complexity
O(T/M)
Space for recursion stack and storing results
โ Linear Space
Constraints
- 1 โค candidates.length โค 30
- 2 โค candidates[i] โค 40
- All elements of candidates are distinct
- 1 โค target โค 40
- The number of unique combinations โค 150
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code