- 斐波那契数、
class Solution {
public int fib(int n) {
/**
确定dp数组以及下标的含义
dp[i]的定义为:第i个数的斐波那契数值是dp[i]
确定递推公式
dp[i] = dp[i - 1] + dp[i - 2];
dp数组如何初始化
dp[0] = 0;
dp[1] = 1;
确定遍历顺序
从前到后遍历的
举例推导dp数组
0 1 1 2 3 5 8 13 21 34 55
*/
if(n<=1) return n;
int a =0,b=1,c=0;
for(int i = 2;i<=n;i++){
c =a + b;
a = b;
b = c;
}
return c;
}
}
- 爬楼梯、
class Solution {
public int climbStairs(int n) {
/**
确定dp数组以及下标的含义
dp[i]的定义为:第i层爬楼梯的方式dp[i]
确定递推公式
dp[i] = dp[i - 1] + dp[i - 2];
dp数组如何初始化
dp[1] = 1;
dp[2] = 2;
确定遍历顺序
从前到后遍历的
举例推导dp数组
1,2,3,5,8
*/
if(n<=2) return n;
int a =1,b=2,c=0;
for(int i = 3;i<=n;i++){
c = a+b;
a = b;
b = c;
}
return c;
}
}
- 使用最小花费爬楼梯
class Solution {
public int minCostClimbingStairs(int[] cost) {
/**
确定dp数组以及下标的含义
dp[i]的定义为:爬到第i曾的花费cost[i]
确定递推公式,这是个累计值
dp[i] = Math.min(dp[i - 1] + cost[i-1] , dp[i - 2]+cost[i-2]);
dp数组如何初始化
dp[0] = 0;
dp[1] = 1;
确定遍历顺序
从前到后遍历的
举例推导dp数组
1,2,3,5,8
*/
int[] dp = new int[cost.length + 1];
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];
}
}