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];
    }
    };
  • 相关阅读:
    Oc中UIKit框架的继承结构
    iOS中的事件传递和响应者链
    音频视频,音乐,录音参考资料
    对象序列化(对对象的归档NSKeyedArchiver、接档NSKeyedUnarchiver)的理解
    iOS--UI篇——UIToolbar的简单使用
    iOS--内购的使用方法
    协调-分布式锁
    协调-协调架构原理
    协调-分布式配置
    队列-生产者消费者模式
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12041227.html
Copyright © 2011-2022 走看看