322. Coin Change

https://leetcode.com/problems/coin-change/description/
解题思路:

  1. 用动态规划:dp[i] represents the total coin change number for amount of i.
  2. dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);

代码:
class Solution {
public int coinChange(int[] coins, int amount) {

    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);
    dp[0] = 0;
    for (int i = 1; i <= amount; i++){
        for(int j = 0; j < coins.length; j++){
            if(i >= coins[j]){
                dp[i] = Math.min(dp[i], dp[i-coins[j]] + 1);
            }
        }
    }
    return dp[amount]>amount?-1:dp[amount];
}

}

你可能感兴趣的:(322. Coin Change)