509. 斐波那契数
- 刷题https://leetcode.cn/problems/fibonacci-number/description/
- 文章讲解https://programmercarl.com/0509.%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
- 视频讲解https://www.bilibili.com/video/BV1f5411K7mo/?vd_source=af4853e80f89e28094a5fe1e220d9062
题解:
java
class Solution {
//非状态压缩
//dp数组含义:代表斐波那契数列元素
public int fib(int n) {
//该数列由0、1开始
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. 爬楼梯
- 刷题https://leetcode.cn/problems/climbing-stairs/description/
- 文章讲解https://programmercarl.com/0070.%E7%88%AC%E6%A5%BC%E6%A2%AF.html
- 视频讲解https://www.bilibili.com/video/BV17h411h7UH/?vd_source=af4853e80f89e28094a5fe1e220d9062
题解:
java
class Solution {
//等同于斐波那契数列
//dp数组元素代表:爬到当前楼层的方法种数
public int climbStairs(int n) {
int[] dp = new int[n + 1];
//初始化0层也为1
dp[0] = 1;
//爬到1层只有1种方式
dp[1] = 1;
for(int i = 2; i <= n; i++){
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
746. 使用最小花费爬楼梯
- 刷题https://leetcode.cn/problems/min-cost-climbing-stairs/description/
- 文章讲解https://programmercarl.com/0746.%E4%BD%BF%E7%94%A8%E6%9C%80%E5%B0%8F%E8%8A%B1%E8%B4%B9%E7%88%AC%E6%A5%BC%E6%A2%AF.html
- 视频讲解https://www.bilibili.com/video/BV16G411c7yZ/?vd_source=af4853e80f89e28094a5fe1e220d9062
题解:
java
class Solution {
//dp数组代表爬到当前楼层的最小花费
//tips:第一步不支付费用
public int minCostClimbingStairs(int[] cost) {
int len = cost.length;
int[] dp = new int[len + 1];
//从下标0或者1开始,故费用均为0
dp[0] = 0;
dp[1] = 0;
//计算
for(int i = 2; i <= len; i++){
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[len];
}
}