C++ 0518.cpp
class Solution {
public:
int change(int amount, vector<int>& coins) {
vector<int> ways, next;
ways.resize(amount + 1, 0);
ways[0] = 1;
for (auto c : coins)
{
next = ways;
for (int base = 0; base < amount; base++)
{
if (ways[base] == 0)
continue;
for (int sum = base + c; sum <= amount; sum += c)
next[sum] += ways[base];
}
swap(ways, next);
}
return ways[amount];
}
};
Difficulty
and has an acceptance rate of about 60% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation solves the classic coin-change counting problem: given a target amount and a list of coin denominations, it computes how many distinct combinations of those coins sum to the target. The algorithm builds the solution incrementally, processing each coin type one after another and maintaining a dynamic programming table that records the number of ways to reach every intermediate sum.
Core Logic
Initialization of the DP table
vector<int> ways, next;
ways.resize(amount + 1, 0);
ways[0] = 1;
A one-dimensional vector ways of length amount + 1 is allocated and filled with zeros. The entry for sum zero is set to one, representing the empty combination that yields a total of zero. This base case enables the subsequent accumulation of counts.
Iteration over each coin denomination
for (auto c : coins)
{
next = ways;
// inner loops
swap(ways, next);
}
The outer loop extracts each coin value c from the input vector. For every coin, a copy of the current state (ways) is stored in next. This copy serves as the destination for updated counts while preserving the original values needed for the inner computation. After processing the current coin, the two vectors are swapped, making the freshly computed next the new source for the next iteration.
Propagation of counts for a specific coin
for (int base = 0; base < amount; base++)
{
if (ways[base] == 0)
continue;
for (int sum = base + c; sum <= amount; sum += c)
next[sum] += ways[base];
}
The inner loops walk through every possible intermediate sum base. If there are no ways to achieve base (ways[base] == 0), the algorithm skips further work for that base, avoiding unnecessary arithmetic. When a valid base is found, a secondary loop adds the current coin repeatedly, generating all reachable sums sum that extend base by multiples of c. For each such sum, the count from ways[base] is added to next[sum], thereby accumulating the number of distinct ways that include the current coin.
Final result extraction
return ways[amount];
After all coin denominations have been processed, the entry ways[amount] holds the total number of combinations that sum exactly to the target amount, which is returned to the caller.
Edge Cases Handled
When the target amount is zero, the initialization ways[0] = 1 ensures the function returns one, reflecting the single valid combination: using no coins. If the coin list is empty, the outer loop never executes; the DP table remains unchanged except for the base case, so the function correctly yields zero for any positive amount and one for amount zero. The inner continue statement protects against attempts to propagate from a base with zero ways, which naturally occurs when certain sums are unreachable with the processed subset of coins. The condition sum <= amount in the innermost loop guarantees that the algorithm never writes beyond the allocated vector bounds, even when a coin value exceeds the remaining amount.
Performance Optimizations
The algorithm reuses two vectors (ways and next) throughout the computation, avoiding repeated allocation of fresh storage for each coin. By copying ways into next once per outer iteration and then swapping the references, the code eliminates the need for element-wise copying after the inner loops complete. The early continue when ways[base] equals zero prevents the inner accumulation loop from executing for unreachable bases, reducing the number of arithmetic operations dramatically when the coin set contains large denominations relative to the target. The step size sum += c in the innermost loop leverages the arithmetic progression of reachable sums for a given coin, ensuring that each reachable sum is visited exactly once per base, which streamlines the update process. Overall, the design balances memory usage and computational effort by maintaining a compact DP table and minimizing redundant work.
ELI5 - Simplified Explanation
Imagine having a big pile of snacks you want to share, but you need to give someone exactly the right amount. You have different types of coins, and each type is worth a different number of treats. This code is like a smart little robot helper that figures out all the different ways you could pick your coins to reach that exact total amount.
The robot starts by creating a long line of empty boxes, numbered from zero all the way up to the total number of treats you need. It puts a special marker in the first box to show that there is one way to have zero treats, which is by doing absolutely nothing. Then, the robot looks at each type of coin one by one. For every coin, it thinks about all the ways it already found and tries adding that coin over and over again to see if it can reach new numbers.
Every time the robot decides to use a coin, it counts how many ways it can reach each new total and keeps track of those numbers in a fresh set of boxes. It swaps the old boxes for the new ones, making sure it remembers every possibility it discovered. By the time it looks at every single coin, the box at the very end of the line holds the total count of all the ways to combine those coins to get exactly what you wanted.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Go | Java | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | begeekmyfriend | C | ||||||||
| BigEggStudy | C# | |||||||||
| everthis | JS | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| everthis | JavaScript | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2218: Maximum Value of K Coins From Piles
- problem 2585: Number of Ways to Earn Points
- problem 2902: Count of Sub-Multisets With Bounded Sum
- problem 2915: Length of the Longest Subsequence That Sums to Target
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality