Coin Change II

medium array dp

Problem

Given coins of distinct denominations and an integer amount, return the number of combinations that make up amount. You may use each coin an unlimited number of times.

Inputamount = 5, coins = [1, 2, 5]
Output4
5, 2+2+1, 2+1+1+1, 1+1+1+1+1.

def change(amount, coins):
    dp = [0] * (amount + 1)
    dp[0] = 1
    for c in coins:
        for x in range(c, amount + 1):
            dp[x] += dp[x - c]
    return dp[amount]
function change(amount, coins) {
  const dp = new Array(amount + 1).fill(0);
  dp[0] = 1;
  for (const c of coins) {
    for (let x = c; x <= amount; x++) {
      dp[x] += dp[x - c];
    }
  }
  return dp[amount];
}
class Solution {
    public int change(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for (int c : coins) {
            for (int x = c; x <= amount; x++) {
                dp[x] += dp[x - c];
            }
        }
        return dp[amount];
    }
}
int change(int amount, vector<int>& coins) {
    vector<int> dp(amount + 1, 0);
    dp[0] = 1;
    for (int c : coins) {
        for (int x = c; x <= amount; x++) {
            dp[x] += dp[x - c];
        }
    }
    return dp[amount];
}
Time: O(amount · |coins|) Space: O(amount)