Java基础知识强化之IO流笔记12:递归之递归解决问题的思想(图解)

1. 使用递归计算5!的结果,递归思想的本质如下:

2. 下面就要使用代码实现这个递归:

递归实现分析:

(1)做递归要写一个方法

(2)出口条件

(3)规律

代码实现如下:

 1 package com.himi.diguidemo;
 2 
 3 /*
 4  * 需求:代码实现求5的阶乘
 5  * 两种方法:
 6  *   A:循环实现
 7  *   B:递归实现(分解法 和  合并法)
 8  */
 9 
10 public class DiGuiDemo {
11 
12     public static void main(String[] args) {
13         //循环实现
14         int jc =1;
15         for (int i = 2; i <=5; i++) {
16             jc*=i;            
17         }
18         System.out.println("5!="+jc);
19         System.out.println("=============================");
20         //递归实现
21         
22         int result = 0;
23         result = func(5);
24         System.out.println("5!="+result);
25 
26     }
27     
28     public static int func(int n) {
29         if(n==1) {
30             return 1;
31         }else {
32             return n*func(n-1);
33             
34         }
35 
36     }
37 
38 }

运行效果如下:

3. 内存图解:

图1:

图2:

原文地址:https://www.cnblogs.com/hebao0514/p/4850125.html