所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。
??思路分析:本题可以抽象成一个完全背包问题。
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < coins.size(); i++) { // 遍历物品
for (int j = coins[i]; j <= amount; j++) { // 遍历背包容量
if (dp[j - coins[i]] != INT_MAX) {
dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};
复杂度分析:
# include <iostream>
# include <vector>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < coins.size(); i++) { // 遍历物品
for (int j = coins[i]; j <= amount; j++) { // 遍历背包容量
if (dp[j - coins[i]] != INT_MAX) {
dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};
int main() {
//vector<int> coins = { 1, 2, 5 };
vector<int> coins = { 2 };
int amount = 3;
Solution s1;
int result = s1.coinChange(coins, amount);
cout << result << endl;
system("pause");
return 0;
}
end