递 归:
计算机科学中,递归是一种解决计算问题的方法,其中解决方案取决于同一类问题的更小子集
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: 594599620@qq.com
* @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: 594599620@qq.com
* @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);
}
}