Recursion in Java

递归无出口

public class RecursionExample1 {
    public static void p() {
        System.out.println("hello");
        p();
    }

    public static void main(String[] args) {
        p();
    }
}

运行结果

``` Exception in thread "main" java.lang.StackOverflowError ```

递归有出口

public class RecursionExample2 {
    public static int count = 0;

    public static void p() {
        count++;
        if (count <= 5) {
            System.out.println("hello " + count);
            p();
        }
    }

    public static void main(String[] args) {
        p();
    }
}

运行结果

``` hello 1 hello 2 hello 3 hello 4 hello 5 ```

递归求阶乘

public class RecursionExample3 {
    public static int factorial(int n) {
        if (n == 1) {
            return 1;
        } else {
            return (n * factorial(n - 1));
        }
    }

    public static void main(String[] args) {
        System.out.println("Factorial of 5 is: " + factorial(5));
    }
}

运行结果

``` Factorial of 5 is: 120 ```

Fibonacci 系列

public class RecursionExample4 {
    public static int n1 = 0, n2 = 1, n3 = 0;

    public static void printFibonacci(int count) {
        if (count > 0) {
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
            System.out.print(" " + n3);
            printFibonacci(count - 1);
        }
    }

    public static void main(String[] args) {
        int count = 15;
        System.out.print(n1 + " " + n2);
        printFibonacci(count - 2);
    }
}

运行结果

``` 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ```
public class RecursionExample5 {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.print(f(i) + " ");
        }
        System.out.println();
        for (int i = 1; i <= 10; i++) {
            System.out.print(f2(i) + " ");
        }
    }

    /**
     * 递归实现
     */
    public static long f(int n) {
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return f(n - 1) + f(n - 2);
        }
    }

    /**
     * 非递归实现
     */
    public static long f2(int n) {
        int[] a = new int[n + 1];
        a[0] = 0;
        a[1] = 1;
        for (int i = 2; i <= n; i++) {
            a[i] = a[i - 1] + a[i - 2];
        }
        return a[n];
    }
}

运行结果

``` 1 1 2 3 5 8 13 21 34 55 1 1 2 3 5 8 13 21 34 55 ```

参考资料

相关文章:

  • 2022-12-23
  • 2021-11-02
  • 2022-12-23
  • 2021-05-09
  • 2022-12-23
  • 2021-11-07
  • 2022-01-16
猜你喜欢
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2021-12-05
  • 2022-02-12
相关资源
相似解决方案