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

 

posted @ 2015-12-27 21:57  `Liok  阅读(696)  评论(0编辑  收藏  举报