coin change

2017-07-13  本文已影响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;
}
上一篇 下一篇

猜你喜欢

热点阅读