题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/04725edbbd42da7579cf6097851571ed.png)
题解
斐波拉契数列(递归超时)
public static void main(String[] args) {
System.out.println(climbStairs(5));
}
public static int climbStairs(int n) {
if (n < 2) {
return 1;
}
return climbStairs(n-1)+ climbStairs(n-2);
}
(动态规划,记录每一次的状态) 定义一个数组存放,存放斐波拉契数列每一项数据;免去递归调用
public int climbStairs(int n) {
if (n <= 2) {
if (n == 2) {
return 2;
}else {
return 1;
}
}
int[] ints = new int[n+1];
ints[1] = 1;
ints[2] = 2;
for (int i = 3; i < n+1 ; i++) {
ints[i] = ints[i-1]+ints[i-2];
}
return ints[n];
}
(滚动数组)定义2个变量代替数组
class Solution {
public int climbStairs(int n) {
if (n <= 2) {
if (n == 2) {
return 2;
}else {
return 1;
}
}
int n1 = 1;
int n2 = 2;
for (int i = 3; i < n+1 ; i++) {
n2 = n1 +n2;
n1 = n2 -n1 ;
}
return n2;
}
}