The basic idea of recursive algorithm design is:
For a complex problem, decompose the original problem into several relatively simple sub-problems, and continue until the sub-problem is so simple that it can be solved directly, that is, it is the exit of recursiveness, so that the original problem can be recursively solved.
When doing recursive algorithms, you must grasp the exit, that is, you must have a clear recursive end condition when doing recursive algorithms. This is very important. In fact, this exit is very easy to understand. It is just a condition. When this condition is met, we no longer recurse.
The key to grasp is:
(1) Recursive exit
(2) The ground push gradually approaches the exit
Recursion is the behavior of the method itself calling itself. Be careful to write the recursion header, that is, when to exit recursion.
Avoid a vicious cycle.
Example 1, print 1~100 by recursively
package com.lanhuigu.base;public class CursionTest {private static int i = 0;/** * Recursively print 1 to 100 */public static void testCursion01() {i++;// Self-increment if (i <= 100) {// Callback when less than or equal to 100, otherwise the callback will jump out to avoid the dead loop System.out.println(i);testCursion01();// Callback: Call itself} else {System.out.println("Game Over!");}}public static void main(String[] args) {testCursion01();// Print 1~100}}Example 2: Recursively calculate the factorial of a certain number
package com.lanhuigu.base;public class CursionTest {/** * Recursively calculate factorial of a certain number*/public static int testFactorial(int n) {if (n == 1) {return 1;} else {return n*testFactorial(n-1);}}public static void main(String[] args) {System.out.println(testFactorial(5));// Calculate factorial of 5}}Regarding recursive calculation factorials, recursive memory analysis structure diagram:
First set the long line, finally close the line, and then pull the fish ashore.
Summarize
The above is all about the example analysis of Java recursive algorithm in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!