题目链接:322. 零钱兑换
要拿硬币凑钱,硬币无限多,就是完全背包问题,定义dp[i]是要凑的钱i的硬币数,对于当前硬币来说,如果选择了这个硬币,要么要凑的硬币数就变成dp[i-coin]
class Solution {
public:
int coinChange(vector<int> &coins, int amount) {
vector<int> dp(amount + 1,INT_MAX / 2);
dp[0] = 0;
for (auto &coin: coins)
for (int i = coin; i <= amount; ++i)
dp[i] = min(dp[i], dp[i - coin] + 1);
return dp[amount] == INT_MAX / 2 ? -1 : dp[amount];
}
};