</>

518. Coin Change II

Medium NeetCode 150
2-D Dynamic Programming Time O(n*m) Space O(n)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
2-D Dynamic Programming
Time
O(n*m)
Space
O(n)

Standard Solution (C++)

SummaryGiven a target amount and a list of coin denominations (each usable unlimited times), count the total number of distinct combinations of coins that sum exactly to the target amount.

Approach
  • Use a 1-D DP array dp of size amount + 1, where dp[a] stores the number of ways to make amount a.
  • Base case: dp[0] = 1 (one way to make zero — use no coins).
  • For each coin, iterate through all amounts from coin to amount, adding dp[a - coin] to dp[a]. Processing one coin at a time ensures each combination is counted once (order-independent), avoiding permutation duplicates.
  • Final answer is dp[amount].
#include <vector>
using namespace std;

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        // dp[a] = number of distinct combinations summing to a
        vector<int> dp(amount + 1, 0);
        dp[0] = 1; // one way to reach zero: pick nothing

        // outer loop over coins keeps each combination order-independent
        for (int coin : coins) {
            for (int a = coin; a <= amount; ++a) {
                dp[a] += dp[a - coin];
            }
        }

        return dp[amount];
    }
};
Time O(n * m) where n = amount and m = number of coins Space O(n) where n = amount

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
using namespace std;

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        // use dynamic programmming to update the number of combinations
        vector<int> dp(amount+1, 0);

        // initialize
        dp[0]=1;

        for(int coin: coins){ // 1, 2, 5
            for(int i=1; i<amount+1; i++){ // i: 1 to 5
                if(i-coin>=0){
                    dp[i]+=dp[i-coin];
                }
            }
        }

        return dp[amount];
    }
};

// Time Complexity: O(n*m) where n is the amount and m is the number of coins
// Space Complexity: O(n)
Time O(n*m) Space O(n)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern