美文网首页
coin change

coin change

作者: 极速魔法 | 来源:发表于2017-07-13 09:51 被阅读26次

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

#include <iostream>
#include <vector>
#include <algorithm>
#pragma GCC diagnostic error "-std=c++11"
using namespace std;

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        vector<vector<int>> memo(coins.size(),vector<int>(amount+1,amount+1));
        int row=coins.size();
        int column=amount+1;
        if(row==0){
            return -1;
        }

        sort(coins.begin(),coins.end());
        //init,line
        memo[0][0]=0;
        for(int j=1;j<=amount;j++){
            if(j%coins[0]==0){
                memo[0][j]=j/coins[0];
            } 
        }

        for(int i=1;i<row;i++){
            for(int j=0;j<amount+1;j++){
                int last=memo[i-1][j];
                if(j-coins[i]>=0 ){
                    memo[i][j]=min(last,memo[i][j-coins[i]]+1);
                } else{
                    memo[i][j]=last;
                }
            }
        }
        return memo[row-1][amount]==amount+1 ? -1:memo[row-1][amount];
    }
};

int main(){
    int amount=6249;
    int arr[]={186,419,83,408};
    vector<int> coins(arr,arr+sizeof(arr)/sizeof(int));

    cout<<Solution().coinChange(coins,amount)<<endl;
    return 0;
}

相关文章

  • leetcode-12

    Coin Change Boundary: There may be no possible change, so...

  • Coin Change

    题目You are given coins of different denominations and a to...

  • Coin Change

    题目来源一道简单的DP题,n种硬币,要求组成某个数值的硬币数最少,代码如下: 看了下讨论区,感觉可以写的更简洁一下...

  • coin change

    最简单的DP

  • coin change

    You are given coins of different denominations and a tota...

  • 322、Coin Change

    参考 [LeetCode] Coin Change 硬币找零 题目描述:You are given coins o...

  • LeetCode Coin Change

    You are given coins of different denominations and a tota...

  • coin change问题

    最简单的模式,不限定硬币使用的次数! 符合动态规划的要求,最优子问题。即10块的时候最优,必然要求小于10块都是最...

  • Coin Change 2

    题目来源给一个钱数以及一些硬币,硬币可以无限取,问有多少种组合方案。一看就是一道DP题,但是太久没刷题,手生。导致...

  • Coin Change 2

    You are given coins of different denominations and a tota...

网友评论

      本文标题:coin change

      本文链接:https://www.haomeiwen.com/subject/logbhxtx.html