53.Coin Change(找硬币)

Level:

  Medium

题目描述:

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Note:
You may assume that you have an infinite number of each kind of coin.

思路分析:

  动态规划的思想,我们用dp[ i ] 代表,当amount的为 i 时的最小找零数,dp[ 0 ]=0。那么 dp[ i ]我们初始化为 amount+1,因为dp[ i ]的最大值不超过amount(只有零钱1元的情况),则状态转移方程为if(coins[t]<=i) dp[ i ]=min(dp[ i ],dp[ i-coins[ t ]]+1)。最后判断dp[amount],如果大于amount,那么返回-1,否则返回dp[amount]。

代码:

public class Solution{
    public int coinChange(int []coins,int amount){
        if(coins==null||coins.length==0||amount<0)
            return -1;
        int []dp=new int[amount+1];
        dp[0]=0;
        for(int i=1;i<dp.length;i++){
            dp[i]=amount+1;//初始化dp[i]
        }
        for(int j=1;j<=amount;j++){
            for(int t=0;t<coins.length;t++){
                if(coins[t]<=j){
                    dp[j]=Math.min(dp[j],dp[j-coins[t]]+1);//状态转移可以这样理解,如果amount==11,如果现在取到一个五块,那么只要知道dp[6],则dp[11]就是dp[6]+1;
                }
            }
        }
        return (dp[amount]>amount)?-1:dp[amount];
    }
}
posted @ 2019-06-26 11:29  yjxyy  阅读(230)  评论(0编辑  收藏  举报