0
点赞
收藏
分享

微信扫一扫

有n个台阶的楼梯,有人可以1次走1步,也可以走两步,也可以走三步,问有多少种走法?



交流群里有个小姐姐问了个问题:

有n个台阶的楼梯,有人可以1次走1步,也可以走两步,也可以走三步,问有多少种走法?

显然这个是斐波那契数列,表达式为 f(n)=f(n-1)+f(n-2)+f(n-3)

好久没写代码了,写个demo,分享一哈


package com.coding.demo;

public class StepDemo {
/*
递归的思想:
走1步则还剩余n-1个台阶,
走2步则还剩余n-2个台阶,
走3步则还剩余n-3个台阶。
分别接着去求出n-1、n-2、n-3个台阶的走法
*/

public static int StepCompute(int step){

if(step == 0){
return 0;
} else if(step == 1){
return 1;
} else if(step == 2){
return 2;
} else if(step == 3){
return 3;
} else {
return StepCompute(step - 1) + StepCompute(step - 2) + StepCompute(step - 3);
}

/*
switch (step){
case 0:
case 1:
return 1;
case 2:
return 2;
case 3:
return 3;
default:
return StepCompute(step - 1) + StepCompute(step - 2) + StepCompute(step - 3);
}
*/

}

public static void main(String[] args){

int rs = StepCompute(10);
System.out.println(rs);

}

}

不喜勿喷!



举报

相关推荐

0 条评论