转载请注明出处:
http://write.blog.csdn.net/postedit/77619703
问题:
https://leetcode.com/problems/coin-change/description/
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.
C++版1:
https://discuss.leetcode.com/topic/32519/6-7-lines-2-ways/2
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, amount+1);
dp[0] = 0;
for (int a = 1; a<= amount; a++)
for (int c : coins)
if (c <= a)
dp[a] = min(dp[a], dp[a-c] + 1);
return dp.back() > amount ? -1 : dp.back();
}
C++版2:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, amount+1);
need[0] = 0;
for (int c : coins)
for (int a=c; a<=amount; a++)
dp[a] = min(dp[a],dp[a-c] + 1);
return dp.back() > amount ? -1 : dp.back();
}
思路:
这题题是典型的一维动态规划问题,答案不难理解
dp[i]是满足总金额为 i的最少钱币数。核心思路是:
need[a] = min( dp[a], dp[a-c] + 1 )
举个例子,假设可供选择的钱币有1、5、10、20、50元,那么 255 元需要最少的钱币数如下:
min1 = dp[ 255 - 1 ] + 1;
min2 = dp[ 255 -5 ] + 1;
min3 = dp[ 255 - 10 ] + 1;
min4 = dp[ 255 - 20 ] + 1;
min5 = dp[ 255 - 50 ] + 1;
dp[ 255 ] = min(min1, min2, min3, min4, min5);
这里有个细节问题的是,coins 可以放在外层循环中,速度可能更快,因为coins 相对 amount 要少的多,
放在外层的话,内层循环切换到外层循环的次数就少。