70. 爬楼梯 (进阶)
题目链接:https://leetcode.cn/problems/climbing-stairs/
代码:
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n+1,0);
dp[0] = 1;
for(int i = 0; i <= n; i++)
{
for(int j = 1; j <= 2 ;j++)
{
if(i >= j)
{
dp[i] += dp[i-j];
}
}
}
return dp[n];
}
};
https://programmercarl.com/0070.爬楼梯完全背包版本.html#思路
322. 零钱兑换
题目链接:https://leetcode.cn/problems/coin-change/
代码:
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],dp[j-coins[i]] + 1);
}
}
if (dp[amount] == INT_MAX) return -1;
return dp[amount];
}
};
本题钱币数量可以无限使用,那么是完全背包。所以遍历的内循环是正序
279.完全平方数
题目链接:https://leetcode.cn/problems/perfect-squares/
代码:
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1,INT_MAX);
dp[0] = 0;
for(int i = 1; i*i <= n; i++)
{
for(int j = i*i; j <= n; j++)
{
dp[j] = min(dp[j],dp[j-i*i]+1);
}
}
return dp[n];
}
};