最重要的就是最后一步:如果走一步就需要f(n-1)种,如果走两步就需要f(n-2)种
走一个台阶:1种-f(1)
走两个台阶:2种-f(2)
三个台阶:先走一个台阶f1和最后一次走两个台阶:f(1)
先走二个台阶f2和最后一次走一个台阶:f(2)
f(3)=f(1)+f(2)
四个台阶:先走三个台阶和最后一次走一个:f(3)
先走两个台阶和最后一次两个台阶:f(2)
f(4)=f(2)+f(3)
n个台阶:f(n)=f(n-1)+f(n-2)
package myjava.递归和迭代;
public class Step {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
System.out.println(f(40));
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static int f(int n) throws Exception {
int i = 2;
if (n <1){
throw new IllegalArgumentException("不能传小于1的数");
}
if (n == 1 || n == i){
return n;
}
return f(n-2) + f(n-1);
}
public static int loop(int n){
int one = 2;
int two = 1;
int sum = 0;
if (n <1){
throw new IllegalArgumentException("不能传小于1的数");
}
if (n == 1 || n == two){
return n;
}
for (int i = 3; i <= n; i++) {
sum = one + two;
two = one;
one = sum;
}
return sum;
}
}