您的位置:首页 > 其它

【LeetCode】322. Coin Change

2016-11-01 20:35 288 查看
Difficulty: Medium

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.

f[i]表示组成和为i的最少数;

f[0]=0;

状态转移方程f[i]=min{ f[ i-nums[j] ] }+1;

算法时间复杂度为O(amount * coins.size() )

class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int i,j,n;
n=coins.size();
if(amount == 0) return 0;
vector<int> f(amount+1,-1);
f[0]=0;
for(i=1;i<=amount;i++)
{
for(j=0;j<n;j++)
{
if(coins[j] <= i && f[i-coins[j]] != -1 && (f[i-coins[j]] < f[i] || f[i] == -1))
f[i] = f[i-coins[j]] + 1;
}
}

return f[amount];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode DP