可爱的小明特别喜欢爬楼梯,他有的时候一次爬一个台阶,有的时候一次爬两个台阶。如果这个楼梯有20个台阶,小明一共有多少种爬法呢?(爬上去后就不能再下来)
运算结果:
1层台阶 ---> 1种爬法
2层台阶 ---> 2种爬法
7层台阶 ---> 21种爬法
方法一: 使用递归完成
/*可爱的小明特别喜欢爬楼梯,他有的时候一次爬一个台阶,有的时候一次爬两个台阶。
如果这个楼梯有20个台阶,小明一共有多少种爬法呢?(爬上去后就不能再下来)*/
//第二层台阶以后, 下一阶的爬法等于前两阶之和
public class Test4 {
public static void main(String[] args) {
System.out.println(getCount(20));
}
private static int getCount(int stairs) {
if (stairs==1){
return 1;
}
if (stairs==2){
return 2;
}
return getCount(stairs-1)+getCount(stairs-2);
}
}
方法二: 不使用递归, 通过循环搭配数组的存储, 在数组中存每一层楼梯的爬法
public class StairsClimbingWays {
public static void main(String[] args) {
// 计算小明爬20个台阶的方法数
int n = 20;
System.out.println("小明有 " + climbStairs(n) + " 种爬法。");
}
// 使用动态规划计算斐波那契数列
public static int climbStairs(int n) {
if (n <= 2) {
return n;
}
int[] ways = new int[n + 1];
// 初始化前两个台阶的走法
ways[1] = 1;
ways[2] = 2;
for (int i = 3; i <= n; i++) {
// 当前台阶的走法是前三个台阶走法的总和
ways[i] = ways[i - 1] + ways[i - 2];
}
return ways[n];
}
}
举一反三: 还有的时候可以一次爬三个台阶, 如果这个楼梯有20个台阶,小明一共有多少种爬法?
/*可爱的小明特别喜欢爬楼梯,他有的时候一次爬一个台阶,有的时候一次爬两个台阶, 还有的时候一次爬三个台阶
如果这个楼梯有20个台阶,小明一共有多少种爬法呢?(爬上去后就不能再下来)*/
//第三层台阶以后, 下一阶的爬法等于前三阶之和
public class Test3 {
public static void main(String[] args) {
System.out.println(getCount(20));
}
private static int getCount(int stairs) {
if (stairs==1){
return 1;
}
if (stairs==2){
return 2;
}
if (stairs==3){
return 4;
}
return getCount(stairs-1)+getCount(stairs-2)+getCount(stairs-3);
}
}