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;

    }

    }

  • 相关阅读:
    this指针详解
    C++处理异常
    C++中的this指针
    c++中的string类
    c面试题总结
    c++中的引用详解
    c++中的new和delete
    函数重载
    BST(二叉排序树)的插入与删除
    ccf行车路线
  • 原文地址:https://www.cnblogs.com/lianggx66/p/4722631.html
Copyright © 2011-2022 走看看