Lintcode 669. 换硬币
这是一道最值型动态规划的典型题目。写状态转移方程时使用max和min。
代码:
class Solution {
public:
/**
* @param coins: a list of integer
* @param amount: a total amount of money amount
* @return: the fewest number of coins that you need to make up
*/
int coinChange(vector<int> &coins, int amount) {
if (0 == coins.size()) return -1;
//初始化
int f[amount + 1];//f[x]代表组成金额为x的最少硬币数
memset(f, 0x3f, sizeof f);
f[0] = 0;
//状态转移
for (int i = 1; i < amount + 1; ++i) {
for (int j = 0; j < coins.size(); ++j) {
if (i >= coins[j] && f[i - coins[j]] != 0x3f3f3f3f)
f[i] = min(f[i], f[i - coins[j]] + 1);
}
}
//最终结果
return f[amount] != 0x3f3f3f3f ? f[amount] : -1;
}
};