leetcode题:518. 零钱兑换 II(中等)

一、题目描述:518. 零钱兑换 II(中等)

给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。 

 

示例 1:

输入: amount = 5, coins = [1, 2, 5]
输出: 4
解释: 有四种方式可以凑成总金额:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
示例 2:

输入: amount = 3, coins = [2]
输出: 0
解释: 只用面额2的硬币不能凑成总金额3。
示例 3:

输入: amount = 10, coins = [10] 
输出: 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-change-2
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路

动态规划,dp[i]表示金额i对所有coins组合总数。dp[i] = \sum dp[i-coins[j]]

三、代码

class Solution {
public:
    int change(int amount, vector<int>& coins) {
        int len = coins.size();
        if(amount == 0)
            return 1;
        //map<string,int> dp;
        vector<int> dp(amount+1,0);
        for(int i = 0;i<len;i++)
        {
            for(int j = coins[i];j<=amount;j++)
            {
                int tmp = j-coins[i];
                
                if(tmp == 0)
                {
                    dp[j] += 1;
                    continue;
                }
                
                if(tmp>0)
                {
                    dp[j]+=dp[tmp];
                }
            }
        }
        return dp[amount];

    }
    
    
    string genk(int amount,int index)
    {
        char s[20];
        sprintf(s,"%d_%d",amount,index);
        return string(s);
    }
    int get_change(int amount,vector<int> & coins,int index,map<string,int>&dp)
    {
       
        if(amount<0 )
            return 0;
        if(amount == 0)
            return 1;
        string key = genk(amount,index);
        if(dp.count(key)>0)
            return dp[key];
        if(index >= coins.size())
        {
            return 0;
        }
        int count = 0;
        while(amount >= 0)
        {
      
            
            int count_r = get_change(amount,coins,index+1,dp);
            count+=count_r;
            amount = amount-coins[index];
        }
        dp[key] = count;
        return count;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值