算法 数据结构 什么是递归 递归解决阶乘 阶乘递归代码 递归解决问题 递归反向打印字符串 数据结构(七)

递 归:

            计算机科学中,递归是一种解决计算问题的方法,其中解决方案取决于同一类问题的更小子集

In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem.

  • 深入到最里层叫做

  • 从最里层出来叫做

  • 的过程中,外层函数内的局部变量(以及方法参数)并未消失,的时候还可以用到

阶乘:

package com.nami.algorithm.study.day06;

/**
 * beyond u self and trust u self.
 *
 * @Author: lbc
 * @Date: 2023-09-05 8:59
 * @email: [email protected]
 * @Description: keep coding
 */
public class Factorial {

    /**
     * 阶乘递归
     * 
     * @param n
     * @return
     */
    private static int f(int n) {
        // 缩减至无须递归
        // 内层函数调用(子集处理)完成,外层函数才能算调用完成
        if (n == 1) {
            return 1;
        }
        //每次调用,函数处理的数据会较上次缩减(子集),而且最后会缩减至无需继续递归
        return n * f(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(f(5));
    }

}

递归 反向打印字符串:

package com.nami.algorithm.study.day06;

/**
 * beyond u self and trust u self.
 *
 * @Author: lbc
 * @Date: 2023-09-05 9:27
 * @email: [email protected]
 * @Description: keep coding
 */
public class ReversePrintString {

    /**
     * 降序
     * @param word
     * @param n
     */
    private static void print(String word, int n) {
        if (0 == n) {
            return;
        }
        System.out.println(word.charAt(n-1));
        print(word, n-1);
    }

    /**
     * 升序
     * @param word
     * @param n
     */
    private static void print0(String word, int n) {
        if (n == word.length()) {
            return;
        }
        print0(word, n+1);
        // 逆序放在递归后面
        System.out.println(word.charAt(n));
    }

    public static void main(String[] args) {
        String word = "abcdef";
//        print(word, 6);
        print0(word, 0);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_33919114/article/details/132684487