码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Coin Change

时间:2015-12-27 23:13:27      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

[LeetCode][JavaScript]Coin Change

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/5080971.html

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