zoukankan      html  css  js  c++  java
  • 算法设计与分析-Week12

    题目描述

    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

    解题思路

    本题给出了硬币的面值,要求用最少的硬币组成一个数,组不成就返回-1.
    首先声明一个大小为amount+1的数组fewestCoins,fewestCoins[i]表示组成数字i所需的最少硬币数,组不成则为-1,最后fewestCoins[amount]即为所求。将数组的第一个元素初始化为0,因为使用0个硬币就能组成0这个数,其余元素初始化为最大正整数。状态转移为fewestCoins[i] = min(fewestCoins[i], fewestCoins[i - coins[j]] + 1),其中coins[j]为硬币面值,若没有更新fewestCoins[j],则将其置为-1。

    源代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    大专栏  算法设计与分析-Week12d">class  {
    public:
    int coinChange(vector<int>& coins, int amount) {
    if(amount <= 0) return 0;
    vector<int> fewestCoins(amount + 1, INT_MAX);
    fewestCoins[0] = 0;
    int n = coins.size();
    bool found = false;
    for(int i = 1; i <= amount; i++) {
    found = false;
    for(int j = n - 1; j >= 0; j--) {
    if(coins[j] <= i && fewestCoins[i - coins[j]] != -1) {
    fewestCoins[i] = min(fewestCoins[i], fewestCoins[i - coins[j]] + 1);
    found = true;
    }
    }
    if(!found) fewestCoins[i] = -1;
    }
    return fewestCoins[amount];
    }
    };
  • 相关阅读:
    JSP_内置对象_out
    POJ_2186_Popular Cows_强连通分量
    POJ_2411_Mondriaan's Dream_状态压缩dp
    POJ_2115_扩展欧几里德
    HDU_5690_快速幂,同余的性质
    POJ_1061_扩展欧几里德
    HDU_5833_高斯消元
    Delphi 使用 Datasnap 的几种三层应用技术总结
    BIM 开发商 --广州
    Cola Cloud 基于 Spring Boot, Spring Cloud 构建微服务架构企业级开发平台
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12041227.html
Copyright © 2011-2022 走看看