动态规划
Coin Change
https://leetcode.com/problems/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:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
组成部分1,确定状态
确定状态包括 最后一步,子问题
求最值,求次数
组成部分2,转移方程
搞清楚子问题
f[x] = min{f[x-2]+1, f[x-5]+1, f[x-7]+1}
组成部分3,初始条件和边界情况
f[0] = 0
不要数组越界
const int MAX = 0x3f3f3f3f
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int dp[amount+1];
memset(dp, -1, sizeof(dp));
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (auto coin: coins) {
if (i - coin >= 0 && dp[i-coin] != -1) {
if (dp[i] == -1) dp[i] = dp[i-coin] + 1;
else dp[i] = min(dp[i], dp[i-coin] + 1);
}
}
}
return dp[amount];
}
};
More examples
https://leetcode.com/problems/unique-paths/
https://leetcode.com/problems/jump-game/

浙公网安备 33010602011771号