前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T166-零钱兑换编程题

【leetcode刷题】T166-零钱兑换编程题

作者头像
木又AI帮
发布2019-09-19 10:23:56
7540
发布2019-09-19 10:23:56
举报
文章被收录于专栏:木又AI帮木又AI帮木又AI帮

木又连续日更第2天(2/100)

木又的第166篇leetcode解题报告

动态规划类型第11篇解题报告

leetcode第322题:零钱兑换

https://leetcode.com/problems/coin-change/

【题目】

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3 
解释: 11 = 5 + 5 + 1

示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。

【思路】

对于所有的硬币c,dp[i] = min(dp[i], dp[i-c] + 1)

【代码】

python版本

class Solution(object):
    def coinChange(self, coins, amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        dp = [sys.maxsize] * (amount+1)
        dp[0] = 0
        coins.sort()
        for i in range(1, amount+1):
            for c in coins:
                if i - c < 0:
                    break
                else:
                    dp[i] = min(dp[i], dp[i-c] + 1)
        return dp[-1] if dp[-1] < sys.maxsize-1 else -1

C++版本

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        vector<int> dp(amount+1, amount*10);
        dp[0] = 0;
        for(int i=1; i < amount+1; i++){
            for(auto c: coins){
                if(i - c < 0)
                    continue;
                dp[i] = min(dp[i], dp[i-c] + 1);
            }
        }
        return dp.back() > amount ? -1 : dp.back();
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档