码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode322—Coin Change

时间:2018-11-17 15:58:20      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:The   else   dash   ash   public   cti   amount   code   diff   

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:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: –1
想法:采用动态规划,状态转移表达式为result[amount]=result[amount-coins]+1;
class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int len = coins.size();
        vector<int> result(amount+1);
        result[0] = 0;
        int max = INT_MAX;
        for(int i = 1 ; i <= amount ;i++ ){
            result[i] = max;
            for(int j = 0 ; j < coins.size() ; j++){
                if(i >= coins[j] && result[i-coins[j]]!= max && result[i-coins[j]]+1<result[i]){
                    result[i] = result[i-coins[j]] + 1;
                }
            }
        }
        if(result[amount] == max){
            return -1;
        }else{
            return result[amount];
        }
    }
};

leetcode322—Coin Change

标签:The   else   dash   ash   public   cti   amount   code   diff   

原文地址:https://www.cnblogs.com/tingweichen/p/9973829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!