leetcode笔记:Coin Change
Posted Herbert_Zero
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode笔记: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.
二. 题目分析
题目大意是,给定不同面值的硬币(数值存放在数组coins
)和一个金额总值amount
。编写函数计算凑齐金额总值所最少需要的硬币数目。如果使用已有的硬币无法凑齐指定的金额,返回-1
。
对于本题目,若使用贪心算法是不可行的,因为有可能会错过全局最优解。
该问题可使用动态规划来解决,构建一个数组dp[amount + 1]
用于记录从0 ~ amount
每个数用coins
组合的最小次数(对于每个数,组合次数的上限不可能超过amount + 1
,因此可将数组初始化为amount + 1
,这样,对于某一下标i,只要出现合法的组合,就可以使用min
函数覆盖掉amount + 1
,若执行算法后该下标所对应的值仍为amount + 1
,说明无法在coins
中找出一个组合来表示i)
根据以上思路,可写出状态转移方程:
dp[x + coins] = min(dp[x] + 1, dp[x + coins])
其中dp[x]
代表凑齐金额x
所需的最少硬币数,coins
表示可用的硬币面值,在coins
数组中遍历。
注意在算法执行前,令dp[0] = 0。
discuss中给出了更高效的深搜方法,相对来说代码比较复杂,如下方第二段代码所示。
三. 示例代码
// DP,时间复杂度:O(n*amount)
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount < 0) return -1;
if (amount == 0) return 0;
// 硬币组合个数不可能大于amount,因此若某下标的元素值
// 为amount + 1说明无法用coins里的硬币组合出该下标
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i < amount + 1; ++i)
for (int j = 0; j < coins.size(); ++j)
if (coins[j] <= i)
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
return dp[amount] > amount ? -1 : dp[amount];
}
};
// DFS
class Solution {
public:
int currBestResult;
void solve(const vector<int>::iterator & begin, const vector<int>::iterator & end, int amount, int currCount)
{
// find a solution, update currBestResult if this is better
if(amount == 0) {
if(currBestResult == -1)
currBestResult = currCount;
else
currBestResult = min(currBestResult, currCount);
return;
}
// use up all coin types, no solution
if(begin == end) return;
// can‘t achiveve a solution better than currBestResult, no need to explore more
if(currBestResult != -1 && currBestResult <= amount / *begin + currCount) return;
int count, currAmount;
// start from the largest remaining coin first
for (auto it = begin; it != end; ++it) {
int coin = *it;
// use coin as much as possible, so that we can get a good solution early to save exploration
currAmount = amount % coin;
count = amount / coin;
while(currAmount < amount) {
// find solutions to fill currAmount with smaller coins
solve(it + 1, end, currAmount, count + currCount);
// scale back by one largest coin to extend currAmount to try solve again in the next iteration
currAmount += coin;
count--;
}
}
}
int coinChange(vector<int>& coins, int amount) {
currBestResult = -1;
sort (coins.begin(), coins.end(), greater<int>());
solve(coins.begin(), coins.end(), amount, 0);
return currBestResult;
}
};
四. 小结
动态规划的经典题目,值得学习。
以上是关于leetcode笔记:Coin Change的主要内容,如果未能解决你的问题,请参考以下文章