题目
一个人爬楼梯,他可以一次走一阶或者两阶,输入不同的楼梯数,求有多少种不同的走法?
样例输入
5
8
10
样例输出
8
34
89
三种方法
import java.util.Scanner;
public class Main {
public static int fun1(int n) { //递归方法
if(n == 1 || n==0) {
return 1;
}
return fun1(n-1) + fun1(n-2);
}
static int f[] = new int[100];
public static int fun2(int n) { //去重复计算方法 递归
if(n == 1 || n==0) {
return 1;
}
if(f[n] != 0) {
return f[n];
}
f[n] = fun2(n-1) + fun2(n-2);
return f[n];
}
static int f1[] = new int[100];
public static int fun3(int n) {
f1[1] = 1;
f1[0] = 1;
for(int i = 2; i <= n; i++) { //递推 动态规划
f1[i] = f1[i-1] + f1[i-2];
}
return f1[n];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long start1 = System.currentTimeMillis();
System.out.println( fun1(n));
System.out.println(System.currentTimeMillis() - start1);
long start2 = System.currentTimeMillis();
System.out.println(fun2(n));
System.out.println(System.currentTimeMillis() - start2);
long start3 = System.currentTimeMillis();
System.out.println(fun3(n));
System.out.println(System.currentTimeMillis() - start3);
}
}