zoukankan      html  css  js  c++  java
  • 递归调用

    递归:在一个方法的内部,对自身进行调用,又叫递归调用

    循环和递归都要具有三部分:初始值,终止条件,前进步长

    递归和迭代是等价的

    常见的问题:累加加和(累乘乘积),汉诺塔,斐波那契数列

    public class Recuresion_06 {

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    System.out.println(factorial(10));

    System.out.println("!!!!!!!!!!!!!!!!!!!");

    System.out.println(fibonacci(10));

    System.out.println("!!!!!!!!!!!!!!!!!!!");

    System.out.println(fibIteration(5));

    }

    // 阶乘:factorial

    public static int factorial(int n) {

    if (n == 1) {

    return 1;

    } else {

    System.out.print(n + "*" + (n - 1) + ",");

    return n * factorial(n - 1);

    }

    }

    // 斐波那契数列

    public static int fibonacci(int n) {

    if (n == 1 || n == 2) {

    return 1;

    } else {

    System.out.print((n - 1) + "+" + (n - 2) + ",");

    return fibonacci(n - 1) + fibonacci(n - 2);

    }

    }

    // 斐波那契数列,迭代实现;iteration

    public static long fibIteration(int index) {

    if (index == 1 || index == 2) {

    return 1;

    }

    long f1 = 1l;

    long f2 = 1l;

    long f = 0;

    for (int i = 0; i < index-2; i++) {

    f = f1 + f2;

    f1 = f2;

    f2 = f;

    System.out.print(f2 + "+" + f1 + ",");

    }

    return f;

    }

    }

  • 相关阅读:
    flask helloworld
    (16)centos7 日志文件
    (15)centos7 系统服务
    (14)centos7 进程管理
    (13)centos7 任务计划
    (12)centos7 环境变量配置
    [BZOJ2045]双亲数(莫比乌斯反演)
    bzoj2018 [Usaco2009 Nov]农场技艺大赛
    bzoj 1001 [BeiJing2006]狼抓兔子
    bzoj 5056: OI游戏 最短路树的计数
  • 原文地址:https://www.cnblogs.com/lianggx66/p/4722631.html
Copyright © 2011-2022 走看看