• 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];
        }
    }
    
  • 相关阅读:
    LVS安装配置
    Ansible自动化运维工具的使用
    DHCP中继配置
    简单爬虫
    zlib1.2.8 编译小记
    varnish 4.0编译安装小记
    imdisk命令行使用及配置
    How to say all the keyboard symbols in English and Chinese
    qwt6在Windows下Qt5的编译,安装,初步使用
    4MLinux7.0 服务器配置详解 别名TheSSS
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11088916.html
Copyright © 2020-2023  润新知