• [LeetCode][JavaScript]Coin Change


    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.

    https://leetcode.com/problems/coin-change/


    完全背包,动态规划。

    当前的最优的coin肯定是由之前的某个子问题,再加上一个coin得到的。

    感觉有一大波背包问题马上要来了。

     1 /**
     2  * @param {number[]} coins
     3  * @param {number} amount
     4  * @return {number}
     5  */
     6 var coinChange = function(coins, amount) {
     7     var dp = [0], i , j, min;
     8     for(i = 1; i <= amount; i++){
     9         min = Infinity;
    10         for(j = 0; j < coins.length; j++)
    11             if(i - coins[j] >= 0) 
    12                 min = Math.min(min, dp[i - coins[j]] + 1);
    13         dp[i] = min;
    14     }
    15     return dp[amount] === Infinity ? -1 : dp[amount];
    16 };
  • 相关阅读:
    mysql 取出每科成绩前两名
    mysql 数据库以及sql 的优化
    Twitter开源分布式自增ID算法snowflake
    SVN 冲突
    VUE 入门 1 列表、if判断 、双向绑定
    Roadblock
    最大子序和
    SOLDIERS
    绿豆蛙的归宿
    Place the Robots
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5080971.html
Copyright © 2020-2023  润新知