LeetCode [DP]322. Coin Change

来源:互联网 发布:java技术 编辑:程序博客网 时间:2024/06/06 18:40

题目链接

ou 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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

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

翻译:

每个硬币都有不同的面值和总金额。写一个函数来计算你所需要的最少的硬币数。如果这笔钱不能由硬币的任何组合构成,则返回1。
例1:
硬币= [ 1, 2, 5 ],金额= 11
返回3(11 = 5 + 5 + 1)
例2:
硬币= [ 2 ],金额= 3
返回- 1。//此处 返回-1 很有讲究
注:
你可以假设你有无数种硬币。

方法:

W总金额,nums[]不同的面值金额

利用搜索,通过给定的W总金额减去nums[]中所有可能的面值,用a记录W-nums[i]使用的纸张

min取a中的最小值

搜索中需要计算多种相同的W-nums[i],会导致冗余,利用 bool is[]和sum[]数组,来判断和存储总金额W的纸张数是否算过,如果算过 min=sum[i] 如果没有 则 a=dfs(W-nums[i])+1; min=最小的 a

下面的问题是 如果没有方案返回-1

在没有方案中,直到W-nums[i]<0 此时min=初值,上一层的a=初值+1,上一层的min=Min{min,a}=min=初值

所以可以在 主函数中 判断 dfs(amount)返回值与 min比较,如果相等,则 return -1;否则 return dfs(amount)

代码如下

class Solution {public:    int len;//记录面值个数    bool is[100000]={false};//记录金额W最少的纸张是否计算过    int sum[100000];///金额W需要的最少纸张    int mianzhi[1000];//全局变量 金额面值    int  dfs (int w)    {         if(w == 0)    return 0;        int min = 10000;        int a;//a获得W-mianzhi[i]需要的纸张        if(!is[w])//判断 金额W 需要的面值是否计算过        {           for(int i = 0; i<len; ++i)                {                   if(w>=mianzhi[i])                   {                   a = dfs(w-mianzhi[i])+1;//此处需要思考                   if(a<min) min = a; /min 获得最少纸张a                   }                                 }             is[w]=true;//更新数组 is[]            sum[w]=min;//更新数组 sum[]        }        else            min=sum[w];//以前计算过W所需面值 从数组中取出        return  min;    }     int coinChange(vector<int>&coins,int amount)     {         len = coins.size();     for(int i=0;i<len;i++)         mianzhi[i]=coins[i];         int t;//判断给定方案是否有解         t=dfs(amount);         if(t==10000) return -1;         else         return dfs(amount);    } }; 



原创粉丝点击