蓝桥杯:
小明刚刚看完电影《第39级台阶》,离开电影院的时候,他数了数礼堂前的台阶数,恰好是39级!
站在台阶前,他突然又想着一个问题:
如果我每一步只能迈上1个或2个台阶。先迈左脚,然后左右交替,最后一步是迈右脚,也就是说一共要走偶数步。那么,上完39级台阶,有多少种不同的上法呢?
请你利用计算机的优势,帮助小明寻找答案。
public class Main06台阶递归 {
static int count=0;
static int temp=0;
static void fun(int stair ,int step){
if (stair<0){temp++;return;} //如果 台阶数小于零 即走完
if (stair==0){
//不论何种情况 stair最终都是0
//判断台阶数等于零的时候判断是否是偶数 如果是 就 count++
temp++;
if (step%2==0){
count++;
}
}
//递归
fun(stair-1,step+1);
fun(stair-2,step+1);
}
public static void main(String[] args) {
fun(39,0);
System.out.printf("count=%d\t",count);
System.out.println(temp);
}
}
洛谷(洛谷里面的这个题用递归会超时,仅供参考):
题目描述
楼梯有 N 阶,上楼可以一步上一阶,也可以一步上二阶。
编一个程序,计算共有多少种不同的走法。
public class P1255 {
static Scanner sc=new Scanner(System.in);
static int step=sc.nextInt();
static int count=0;
static int stages=0;
public static void dfs(int step,int stages ){
if (stages>step){
return;
}
if (stages==step){
count++;
return;
}
dfs(step,stages+1);
dfs(step,stages+2);
}
public static void main(String[] args) {
dfs(step,stages);
System.out.println(count);
}
}