509. 斐波那契数
https://leetcode.cn/problems/fibonacci-number/
- 确定dp数组(dp table)以及下标的含义
dp[i] 第i个斐波那契数值为dp[i] - 确定递推公式
题目说了 F(n) = F(n - 1) + F(n - 2) - dp数组如何初始化
题目说了 F(0) = 0,F(1) = 1 - 确定遍历顺序
从前向后遍历 - 举例推导dp数组
- 打印 dp 数组
- 我的答案
class Solution {
public int fib(int n) {
if(n==0) return 0;
if(n==1) return 1;
return fib(n-1)+fib(n-2);
}
}
- 非递归
class Solution {
public int fib(int n) {
if (n <= 1) return n;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int index = 2; index <= n; index++){
dp[index] = dp[index - 1] + dp[index - 2];
}
return dp[n];
}
}
70. 爬楼梯
啊 没思路
如果总共1阶,有1种方法
如果总共2阶,有2种方法
如果总共3阶,他只可能是从1阶或者2阶上来的,1种+2种=3种方法。3阶的前一个状态只可能是2阶或者1阶段(一次走一步或者两步),所以从初始到前一个阶段共有3种方法。
如果总共4阶,4阶的前一个状态只可能是2阶或者3阶段(一次走一步或者两步),所以从初始状态到上一阶段,有2+3=5种
-
思考过程
(1) 确定dp数组(dp table)以及下标的含义:达到第i阶有 dp[i]种方法
(2) 确定递推公式dp[i] = dp[i-1]+dp[i-2]
(3) dp数组如何初始化dp[1] = 1 ; dp[2] = 2
(4) 确定遍历顺序从前到后
(5) 举例推导dp数组
(6) 打印 dp 数组 -
AC
class Solution {
public int climbStairs(int n) {
if(n==1) return 1;
if(n==2) return 2;
int[]dp = new int[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. 使用最小花费爬楼梯
分析:
站在 0的位置,不花费钱,但是往上跳就要花费,【往上跳才需要花费】
顶楼的位置:数组长度+1
- 思考过程
(1) 确定dp数组(dp table)以及下标的含义:达到第i阶,需要的花费为dp[i]
(2) 确定递推公式 跳到dp[i]的前一个状态有两种 (1) dp[i-1],(2) dp[i-2] ;
dp[i] = Math.min(dp[i-1] + cost[i-1] , dp[i-2] + cost[i-2])
(3) dp数组如何初始化 dp[0] = 0 ; dp[1] = 0
(4) 确定遍历顺序 从前到后
(5) 举例推导dp数组
(6) 打印 dp 数组
- AC
class Solution {
public int minCostClimbingStairs(int[] cost) {
int top = cost.length;
int[]dp = new int[top+1];
dp[0]=dp[1]=0;
for(int i=2; i<=top; i++) {
dp[i] = Math.min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]);
}
return dp[top];
}
}
2024.10.19重做
dp[1]=0; //这一步要注意,从别的地方跳过来的 不包括当前这个台阶的费用
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[]dp = new int[cost.length+1];
//dp[i]到台阶i的最低花费
dp[0]=0;
dp[1]=0; //这一步要注意,从别的地方跳过来的 不包括当前这个台阶的费用
for(int i=2; i<=cost.length; i++) {
dp[i] = Math.min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]);
}
return dp[cost.length];
}
}
杨辉三角
0905
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i=0; i<numRows; i++) {
List<Integer> tmp = new ArrayList<>();
for(int j=0; j<=i; j++) {
if(j==0 || j==i) {
tmp.add(1);
} else {
tmp.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
}
}
res.add(tmp);
}
return res;
}
}
List<List<Integer>>代替二维数组
574

被折叠的 条评论
为什么被折叠?



