Algo-Sim › Dynamic Programming

Coin Change II

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Count the coin combinations that make an amount. Looping coins outside amounts counts each combination once, not every order.

Problem

Given an integer amount and an array of distinct coin values coins, return the number of combinations of coins that add up to amount. You have an unlimited supply of each coin, and combinations that differ only in order are the same. If no combination works, return 0.

Constraints

Edge cases to test

Follow-up questions

Why do loop orders matter?
Coins outside counts combinations (each multiset once); amounts outside counts ordered sequences (Combination Sum IV).
What is the space cost?
One 1D array of size amount + 1: O(n·amount) time, O(amount) space.

Solution

Java

public int change(int amount, int[] coins) {
    int[] dp = new int[amount + 1];
    dp[0] = 1;
    for (int coin : coins) {
        for (int a = coin; a <= amount; a++) {
            dp[a] += dp[a - coin];
        }
    }
    return dp[amount];
}

Python

def change(amount, coins):
    dp = [0] * (amount + 1)
    dp[0] = 1
    for coin in coins:
        for a in range(coin, amount + 1):
            dp[a] += dp[a - coin]
    return dp[amount]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int change(int amount, vector<int> &coins) {
        vector<int> dp = vector<int>(amount + 1);
        dp[0] = 1;
        for (int coin : coins) {
            for (int a = coin; a <= amount; a++) {
                dp[a] += dp[a - coin];
            }
        }
        return dp[amount];
    }
};

More Dynamic Programming problems