70. 爬楼梯 (进阶)
思路
代码
class Solution {
public:
int climbStairs(int n) {
vector<int> dp (n+1, 0);
dp[0] = 1;
for(int i = 1; i <= n ; i++ ) {
for(int j = 1; j <= 2; j++) {
if(i>=j){
dp[i] += dp[i-j];
}
}
}
return dp[n];
}
};
总结
322. 零钱兑换
思路
代码
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]);
}
}
}
if(dp[amount] == INT_MAX) return -1;
return dp[amount];
}
};
总结
279.完全平方数
思路
代码
class Solution {
public:
int numSquares(int n) {
vector<int> dp (n+1, INT_MAX);
dp[0] = 0;
for(int i = 0; i <= n; i++) {
for(int j = 1; j*j <= i; j++) {
dp[i] = min(dp[i - j*j] + 1, dp[i]);
}
}
return dp[n];
}
};
总结