递归的形式和特点

image.png

  1. package com.key.d2_recusion;
  2. public class RecusionDemo1 {
  3. public static void main(String[] args) {
  4. }
  5. public static void test(){
  6. System.out.println("========test被执行========");
  7. test(); //方法递归,直接递归形式
  8. }
  9. /*
  10. 间接递归
  11. */
  12. public static void test1(){
  13. System.out.println("========test1被执行========");
  14. test2();
  15. }
  16. public static void test2(){
  17. System.out.println("========test2被执行========");
  18. test1();
  19. }
  20. }

递归的算法流程、核心要素

递归算法案例1:计算1-n的阶乘结果,使用递归的思想解决,阶乘公式:f(n)=1234…(n-1)*n
image.png

  1. package com.key.d2_recusion;
  2. public class RecusionDemo2 {
  3. public static void main(String[] args) {
  4. System.out.println(method1(3));
  5. }
  6. public static int method1(int n){
  7. if (n == 1){
  8. return 1;
  9. }else {
  10. return method1(n-1) * n;
  11. }
  12. }
  13. }

image.png

递归三要素:

image.png

递归的经典问题

猴子吃桃问题

image.png

  1. package com.key.d2_recusion;
  2. public class RecusionDemo3 {
  3. public static void main(String[] args) {
  4. System.out.println(sum(10));
  5. }
  6. public static int sum(int n){
  7. if (n == 1){
  8. return 1;
  9. }else {
  10. return (sum(n-1)+1)*2;
  11. }
  12. }
  13. }

image.png

非规律化递归问题

查找计算机中的文件,类似于搜索器

image.png

  1. package com.key.d2_recusion;
  2. import java.io.File;
  3. /*
  4. 实现搜索文件功能,/Users/p0wer_shell/Desktop/图片/123.txt
  5. */
  6. public class RecusionDemo4 {
  7. public static void main(String[] args) {
  8. //2、传入目录和文件名
  9. File dir_path = new File("/Users/p0wer_shell/Desktop/");
  10. String file_name = "123.txt";
  11. searchFile(dir_path,file_name);
  12. }
  13. /**
  14. * 1、搜索某个目录下的全部文件,找到我们想要的文件
  15. * @param dir 被搜索的源目录,在哪个目录下搜索
  16. * @param fileName 要搜索的文件名
  17. */
  18. public static void searchFile(File dir,String fileName){
  19. //3、判断dir是否是目录
  20. if (dir.isDirectory() && dir != null){
  21. //4、提取当前目录下的一级文件对象
  22. File[] files = dir.listFiles();
  23. //5、判断是否存在一级对象,如果存在才能遍历
  24. if (files != null && files.length > 0){
  25. for (File file : files) {
  26. //6、判断当前遍历的是文件夹还是文件
  27. if (file.isFile()){
  28. //7、是不是我们要找的文件,如果是就输出他的路径
  29. if (file.getName().contains(fileName)){ //判断文件名是否包含我们要找的关键字
  30. System.out.println(file.getAbsolutePath());
  31. }
  32. }else {
  33. //8、匹配的是文件夹,需要继续找文件,这里可以用递归的方法
  34. searchFile(file,fileName);
  35. }
  36. }
  37. }
  38. }else {
  39. System.out.println("当前输入有误,请输出文件夹...");
  40. }
  41. }
  42. }

image.png