• Leetcode 322. 零钱兑换 dp


    地址 https://leetcode-cn.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
    
    
    示例 3:
    输入:coins = [1], amount = 0
    输出:0
     
    
    提示:
    1 <= coins.length <= 12
    1 <= coins[i] <= 231 - 1
    0 <= amount <= 104
    

    解答

    使用动态规划解决该题
    设dp[i]表示 金额i使用的最小硬币数
    可以使用的硬币金额 分别为x1 x2 x3 ~~~xn
    那么 dp[i] = min(dp[i-x1]+1,dp[i-x2]+1,~~~,dp[i-xn]+1);
    
    class Solution {
    public:
        int dp[10010];
        int coinChange(vector<int>& coins, int amount) {
            memset(dp,0x3f,sizeof dp);
            sort(coins.begin(),coins.end());
            dp[0]=0;
            for(int i= 1; i <=amount;i++ ){
                for(auto& e:coins){
                    if(e>i)break;
                    dp[i]=min(dp[i],dp[i-e]+1);
                }
            }
            if(dp[amount]==0x3f3f3f3f) dp[amount]=-1;
            return dp[amount];
        }
    };
    

    我的视频题解空间

  • 相关阅读:
    申请奖励加分
    寒假学习01
    加分项及建议
    12月30日总结
    12月17日 期末总结
    12月31日总结
    12月15日总结
    12月28日总结
    01月03日总结
    01月05日总结
  • 原文地址:https://www.cnblogs.com/itdef/p/15866668.html
Copyright © 2020-2023  润新知