博客
关于我
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 yaml.dump 缩进错误
    查看>>
    Python yield generator
    查看>>
    Python yield 使用浅析
    查看>>
    Python yield解析:深入理解生成器的魔力
    查看>>
    Python You are using pip version 10.0.1, however version 19.3.1 is available.
    查看>>
    python zipfile模块学习笔记(一)
    查看>>
    Python zip函数 详解(全)
    查看>>
    Python \r\n与\n的转换
    查看>>
    python __new__中单例的作用
    查看>>
    python | aiofiles,一个超酷的 Python 库!
    查看>>
    python | akshare,一个超强的 开源Python 金融数据接口库!
    查看>>
    python | alabaster,一个强大的 关于alabaster 主题 Python 库!
    查看>>
    python | algorithms,一个超赞的 集合常用算法的Python 库!
    查看>>
    python调用jpype 报错:OSError JVM is already started和JVM cannot be restarted
    查看>>
    python | authlib,一个强大的 Python 库!
    查看>>
    python | awswrangler,一个高效的 Python 库!
    查看>>
    python | bashplotlib,一个有趣的Python库!
    查看>>
    python | bentoml,一个超级厉害的 模型部署 Python 库!
    查看>>
    python调用jar包的模块_python调用jar包
    查看>>
    python | black,一个神奇的 代码格式化工具 Python 库!
    查看>>