其他分享
首页 > 其他分享> > Leetcode 322 Coin Change DP

Leetcode 322 Coin Change DP

作者:互联网

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

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

Solution

设 \(dp[i]\) 表示 \(amount = i\) 的最小组成数,转移的话很显然就是枚举每一个小于 \(amount\) 的钱币:

\[dp[i] = \min(dp[i], dp[i-\text{coins}[j]]+1) \]

点击查看代码
class Solution {
private:
    int dp[10004];
    
public:
    int coinChange(vector<int>& coins, int amount) {
        if(amount==0)return 0;
        int n = coins.size();
        int MAX = 9999999;
        for(int i=0;i<=amount;i++)dp[i] = MAX;
        for(int j=0;j<n;j++){
            if(amount>=coins[j])dp[coins[j]]=1;
        }
        
        for(int i=1;i<=amount;i++){
            for(int j=0;j<n;j++){
                if(coins[j]<=i){
                    dp[i] = min(dp[i], 1 + dp[i-coins[j]] );
                }
            }
        }
        if(dp[amount]>amount)return -1;
        else return dp[amount];
    }
};

标签:return,int,money,coins,322,amount,dp,Coin,DP
来源: https://www.cnblogs.com/xinyu04/p/16272116.html