zoukankan      html  css  js  c++  java
  • LeetCode 322. Coin Change

    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.

    class Solution { //完全背包问题
    public:
        const int inf = 9999999;
        int coinChange(vector<int>& coins, int amount) {
            vector<int> cnt(amount+1, inf);
            cnt[0] = 0;
            for(int i=0; i<coins.size(); i++)
                for(int j = coins[i]; j<=amount; j++)
                    //if(j == coins[i] )
                       // cnt[j] = 1;
                    //else
                        //cnt[j] = min(cnt[j], cnt[j-coins[i]]+1);
                    cnt[j] = (j == coins[i])? 1: min(cnt[j], cnt[j - coins[i]]+1);
            return cnt[amount] == inf? -1: cnt[amount];
        }
    };
    
  • 相关阅读:
    SPOJ NDIV
    SPOJ ETF
    SPOJ DIVSUM
    头文件--持续更新
    SPOJ FRQPRIME
    SPOJ FUNPROB
    SPOJ HAMSTER1
    观光
    最短路计数
    拯救大兵瑞恩
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061093.html
Copyright © 2011-2022 走看看