【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
Example 1:
coins =
return
Example 2:
coins =
return
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];
}
};
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 322. Coin Change
- Leetcode 322. Coin Change
- Leetcode 322. Coin Change
- LeetCode322. Coin Change
- leetcode 322. Coin Change
- [leetcode] 322. Coin Change 解题报告
- leetcode 322. Coin Change
- Leetcode 322. Coin Change
- leetcode 322. Coin Change
- LeetCode 322. Coin Change Python 动态规划/BFS解法
- LeetCode 322. Coin Change
- [Leetcode] 322. Coin Change 解题报告
- leetcode 322. Coin Change 解题思路 C语言
- leetcode 322. Coin Change
- leecode 解题总结:322. Coin Change
- 322. Coin Change
- 322. Coin Change
- leetcode322 coin change & leetcode343 integer break
- 动态规划——322. Coin Change
- LeetCode "Coin Change"