有n步台阶,一次只能上1步或者2步,共有多少种走法?
法一:递归
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(upStep(40));
long end = System.currentTimeMillis();
System.out.println(end - start);
}
public static int upStep(int n) {
if(n ==1 || n == 2) return n;
else return upStep(n-1) + upStep(n-2);
}
//输出:
165580141
653
改进一下,以为状态转移为f(n) = f(n-1) +f(n-2),递归没有复用之前的结果,每次都从n-k递归到1、2,浪费了性能,
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(upStep(40));
long end = System.currentTimeMillis();
System.out.println(end - start);
}
public static int upStep(int n) {
if(n ==1 || n == 2) return n;
//初始化,sum为f(n),one为f(n-1),two为f(n-2)
int one = 2;
int two = 1;
int sum = 0;
for(int i = 3;i <= n;i ++) {
//f(n) = f(n-1) +f(n-2)
sum = one + two;
//f(n-2) = f(n-1),台阶++,状态也需要升级
two = one;
//f(n-1) = f(n),升级
one = sum;
}
return sum;
}
//输出:
165580141
1
提升明显
传送门:https://www.bilibili.com/video/BV1nJ411M7ZJ?p=5