博客
关于我
java 基础编程练习6
阅读量:713 次
发布时间:2019-03-21

本文共 558 字,大约阅读时间需要 1 分钟。

小乐乐走楼梯的方法数遵循斐波那契数列的规律。当n=1时,只有一种方法;当n=2时,有两种方法。对于更大的n,方法数等于前一阶楼梯的方法数加上第二阶楼梯的方法数,这正是斐波那契数列的定义。通过递归计算,我们可以得到小乐乐的方法数。

具体步骤如下:

  • 当n=1时,返回1。
  • 当n=2时,返回2。
  • 否则,递归调用fun(n-1)和fun(n-2)并相加返回结果。
  • 代码如下:

    public class Main {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int n = in.nextInt();        System.out.print(fun(n));    }    private static int fun(int n) {        if (n == 1) {            return 1;        } else if (n == 2) {            return 2;        } else {            return fun(n - 1) + fun(n - 2);        }    }}

    转载地址:http://rbjrz.baihongyu.com/

    你可能感兴趣的文章
    Python Sphinx自动摘要:成员函数的自动列表
    查看>>
    Python SQL和NoSQL数据库操作实战
    查看>>
    python stdout flush_sys.stdout.flush()方法的用法
    查看>>
    python string 运算
    查看>>
    Python str与bytes之间的转换
    查看>>
    Python subprocess ffmpeg
    查看>>
    python subprocess Permission denied Errno 13
    查看>>
    Python subprocess.call - 将变量添加到 subprocess.call
    查看>>
    Python Subprocess.Popen 从一个线程
    查看>>
    Python subprocess.Popen 作为 Windows 上的不同用户
    查看>>
    Python转换PPT为PDF
    查看>>
    Python subprocess.Popen() 等待完成
    查看>>
    Python sum 二维列表中具有相同第一个值的元素
    查看>>
    Python Sympy模块NoConversion:收敛到根失败;请尝试n<;15或MaxSteps>;50
    查看>>
    Python sys.MODULES包含尚未导入的模块
    查看>>
    python sys模块使用
    查看>>
    Python tarfile、zipfile解压模块讲解
    查看>>
    python tcp server传输成功之后进行删除_python学习之路(三)使用socketserver进行ftp断点续传...
    查看>>
    python车牌识别系统+车辆管理+计费系统(图像识别)django框架 计算机毕业设计
    查看>>
    Python threading.Thread 只能使用私有方法 self.__Thread_stop() 停止
    查看>>