PAT1-第39级台阶(递归)

xiaoxiao2021-02-28  46

 第39级台阶

小明刚刚看完电影《第39级台阶》,离开电影院的时候,他数了数礼堂前的台阶数,恰好是39级! 站在台阶前,他突然又想着一个问题: 如果我每一步只能迈上1个或2个台阶。先迈左脚,然后左右交替,最后一步是迈右脚,也就是说一共要走偶数步。那么,上完39级台阶,有多少种不同的上法呢? 请你利用计算机的优势,帮助小明寻找答案。

要求提交的是一个整数。

注意:不要提交解答过程,或其它的辅助说明文字。

有(8分)种不同的上法

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

递归

package PAT1; public class Main{ static int count = 0; public static void f(int sy, int step) { if (sy < 0)// sy为剩余的台阶数 return; if (sy == 0) { if (step % 2 == 0)//偶数步 count++; } else { f(sy - 1, step + 1);// 走1台阶 f(sy - 2, step + 1);// 走2台阶 } } public static void main(String[] args) { f(39, 0); System.out.println(count); } }

 

相似题目上台阶:

#include<iostream> using namespace std; int taijie(int n) { //边界 if(n < 0) return 0; if(n == 0) return 1; //递归 return taijie(n-1)+taijie(n-2); } int main() { int n; cin >> n; cout<< taijie(n); return 0; }

 

转载请注明原文地址: https://www.6miu.com/read-2628897.html

最新回复(0)