518. Coin Change 2

Problem:
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Note: You can assume that
  • 0 <= amount <= 5000
  • 1 <= coin <= 5000
  • the number of coins is less than 500
  • the answer is guaranteed to fit into signed 32-bit integer

Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Analysis:
State dp[i][j], combination if 0~i coins to make up amount j.
Transition: if not use i, we look at dp[i - 1][j]
                  if use i, we look at dp[i][j - coins[i - 1]], since coin i can be used infinite times.

If only use i once, we can treat dp[i][j - coins[i - 1]] not use i.

It's easier to under stand with 1D dp array implementation.
dp[i] += dp[i - coin]. Previous dp[i] is the case when not use i. dp[i - coin] is the case use i.
Reference video
Solution:
class Solution {
    public int change(int amount, int[] coins) {
        int[][] dp = new int[coins.length + 1][amount + 1];
        dp[0][0] = 1;
        for (int i = 1; i <= coins.length; i++) {
            dp[i][0] = 1;
            for (int j = 1; j <= amount; j++) {
                dp[i][j] = dp[i - 1][j] + (j >= coins[i - 1] ? dp[i][j - coins[i - 1]] : 0);
            }
        }
        return dp[coins.length][amount];
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array