面试题
编程题:有n步台阶,一次只能上1步或2步,共有多少种走法?
看到这道递归题时,我们一步一步来分析最后得出公式:

image
然后我们就可以写出我们的递归代码
public class Ladder {
public static void main(String[] args) throws Throwable {
//阶梯数
int n = 6;
//有多少种走法
int c = 0;
c = calculate(n);
System.out.println(c);
}
private static int calculate(int n) throws Throwable {
if (n < 1){
throw new Throwable("台阶数不能小于1");
}
if (n ==1 || n == 2){
return n;
}
return calculate(n-2) + calculate(n-1);
}
}
自己的想法
我们首先根据题意,一步步得出符合题意的公式,最好写出关于n的表达式。这样我们在写的时候就比较容易写出递归函数,当然是在简单了解了递归是很什么后。