Algorithm data structure What is recursion Recursive solution Factorial Factorial recursive code Recursive problem solving Recursive reverse printing String data structure (7)

recursion:

            In computer science, recursion is a method of solving computational problems in which the solution depends on a smaller subset of the same type of problem

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.

  • Going deep into the innermost layer is called passing

  • Coming out from the innermost layer is called returning

  • During the recursion process, the local variables (and method parameters) in the outer function do not disappear and can still be used during reversion .

factorial:

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));
    }

}

Recursively print a string in reverse:

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);
    }

}

Guess you like

Origin blog.csdn.net/qq_33919114/article/details/132684487