题目:509.斐波那契数
思路:
1.确定dp[i]含义:第i个斐波拉契数值为dp[i]
2.确定递推公式:dp[i] = dp[i - 1] + dp[i - 2]
3.dp数组如何初始化:d[0] = 1, dp[1] = 1
4.遍历顺序:从前向后
5.打印dp
class Solution {
public:int fib(int n) {if(n <= 1) return n; //这一个返回值不能少,如果测试集n = 0,少了这一步后面dp[1]会越界vector<int> dp(n + 1);dp[0] = 0;dp[1] = 1;for(int i = 2; i <= n; i++){dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];}
};
只维护两个值的方法如下
class Solution {
public:int fib(int n) {if(n <= 1) return n; //这一个返回值不能少,如果测试集n = 0,少了这一步后面dp[1]会越界vector<int> dp(2);dp[0] = 0;dp[1] = 1;int sum;for(int i = 2; i <= n; i++){sum = dp[0] + dp[1];dp[0] = dp[1];dp[1] = sum;}return sum;}
};
题目:70.爬楼梯
思路:
举个例子:想要买走到第5阶,要么从第3阶台阶迈两步走到,要么从第4阶台阶迈一步走到。所以dp[5] = dp[4] + dp[3].
1.dp数组含义:dp[i]代表到达第i阶台阶有dp[i]种方法。
2.递推关系:dp[i] = dp[i -1] + dp[i - 2]
3.dp数组初始化:dp[1] = 1, dp[2] = 2
4.遍历顺序:从前向后
5.打印dp数组
代码如下 :
class Solution {
public:int climbStairs(int n) {if(n == 1) return 1;vector<int> dp(n + 1);dp[1] = 1;dp[2] = 2;for(int i = 3; i <= n; i++){dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];}
};
题目:746.用最小花费爬楼梯
1.dp数组含义:到达第i阶楼梯要花费的体力为dp[i]
2.动态转移方程:dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] = cost[i - 2])
3.初始化:dp[0] = 0, dp[1] = 0
4.遍历顺序
5.打印dp
class Solution {
public:int minCostClimbingStairs(vector<int>& cost) {int n = cost.size() + 1;vector<int> dp(n);dp[0] = 0;dp[1] = 0;for(int i = 2; i < n; i++){dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);}return dp[n - 1];}
};