Java api--Recursion

Source: Internet
Author: User

1. The phenomenon of invoking the method itself in the method definition2, recursive attention to achieve 1) to have an exit, or Die recursion 2) times can not be too many, otherwise memory overflow 3) Construction method can not be used recursively

3. The idea and diagram of solving problems recursively:

Example 1: factorial of 5
 PackageDiguidemos;/*** Created by Gao on 15-12-27.*//** Requirements: Please use code to achieve the factorial of 5. * There are several options to achieve it? * A: Loop implementation * B: recursive implementation * A: Do recursion to write a method * B: Export conditions * C: Law*/ Public classDiGuiDemo01 { Public Static voidMain (string[] args) {intJC = 1;  for(inti = 2; I <= 5; i++) {JC*=i; } System.out.println ("The factorial of 5 is:" + JC);//the factorial of 5 is:The factorial of the System.out.println ("5" is: "+jiecheng (5)); }        /** Do recursion to write a method: * return value type: int * parameter list: int n * Export Condition: * if (n = = 1) {return 1;}     * Rule: * if (n! = 1) {return n method name (n-1);} */     Public Static intJiecheng (intN) {        if(n = = 1){          return1; }Else{            returnn * Jiecheng (n-1); }    }}
Output Result:The factorial of 5 is: the factorial of 1205 is: 120 4,code implementation of recursive factorial and memory plot

5. Recursive exercises1)The Rabbit Problem (Fibonacci series)
 PackageDiguidemos;/*** Created by Gao on 15-12-27.*//** There are a pair of rabbits, from the 3rd month after birth a pair of rabbits each month, the small rabbit to the third month after the birth of a pair of rabbits, if the rabbit is not dead, ask the 20th month of the number of rabbits?  * Analysis: We have to find a way of finding the law * Rabbit logarithm * First month: 1 * Second month: 1 * Third Month: 2 * Fourth Month: 3 * Fifth month: 5 * Sixth month: 8 * ... * This shows that the Rabbit object data is: * 1,1,2,3,5,8 ... * Rule: * A: Starting from the third item, each item is the sum of the first two items * B: And the first two are known * * How do you implement this program? * A: Array Implementation * B: Variable Change implementation * C: Recursive implementation * If the number of rabbits adjacent to the two-month is a, b * The first adjacent data: A=1,b=1 * Second adjacent data: a=1,b=2 * Third adjacent Data: a=2,b=3 * Fourth adjacent data: a=3,b=5 * See: The next time A is the previous B, the next one is the previous a+b*/ Public classDiGuiDemo02 { Public Static voidMain (string[] args) {//define an array        int[] arr =New int[20]; arr[0] = 1; arr[1] = 1;  for(inti = 2; I < 20; i++) {Arr[i]= Arr[i-1] + arr[i-2]; } System.out.println (arr[19]);//6765System.out.println ("-----------------"); intA = 1; intb = 1;  for(inti = 0; I < 18; i++) {            inttemp =A; A=b; b= temp +b; } System.out.println (b); //6765System.out.println ("-----------------"); System.out.println (FIB (20));//6765    }     /** Method: Return value type: int parameter list: int n export condition: First month is 1, second month is 1 rule: starting from the third month, every one months is the first two months of the sum*/     Public Static intFibintN) {if(n = = 1 | | n = = 2) {            return1; } Else {            returnFIB (n-1) + fib (n-2); }    }}

2) Recursive traversal of the file name at the end of the specified suffix name in the directory

 PackageDiguidemos;ImportJava.io.File;/*** Created by Gao on 15-12-27.*//** Requirement: Please put the absolute path of all Java end files in the C:\workspace directory to the output in the console.  * * Analysis: * A: Package directory * B: Get the file array of all files or folders in this directory * C: Traverse the file array to get each file Object * D: Determine if the file object is a folder * Yes: Go back to B * No: Continue to determine if the. Java End * is: the absolute path to the output of the file * No: Ignore it*/ Public classDiGuiDemo03 { Public Static voidMain (string[] args) {//Package CatalogFile Srcfolder =NewFile ("C:\\workspace"); //recursive function Implementationgetalljavafilepaths (Srcfolder); }     Public Static voidgetalljavafilepaths (File srcfolder) {//get file array for all files or folders in this directoryfile[] Filearray =Srcfolder.listfiles (); //iterate over the file array to get each file object         for(File file:filearray) {//determines whether the file object is a folder            if(File.isdirectory ()) {getalljavafilepaths (file); } Else {                //continue to determine whether to end with. Java                if(File.getname (). EndsWith (". Java")) {                    //The absolute path of the file is outputSystem.out.println (File.getabsolutepath ()); }            }        }    }}

3) recursively delete directories with content

 PackageDiguidemos;ImportJava.io.File;/*** Created by Gao on 15-12-27.*//** Requirements: Recursively delete directory with contents * * Directory I have given: C:\JIANZHIOFFER02 * * Analysis: * A: Package directory * B: Get the file array of all files or folders in this directory * C: Traverse the file array to get each file Object * D: Determine if the file object is a folder * Yes: Go back to B * No: Delete*/ Public classDiGuiDemo04 { Public Static voidMain (string[] args) {//Package CatalogFile Srcfolder =NewFile ("C:\\jianzhioffer02"); //Recursive ImplementationDeleteFolder (Srcfolder); }    Private Static voidDeleteFolder (File srcfolder) {//get file array for all files or folders in this directoryfile[] Filearray =Srcfolder.listfiles (); if(Filearray! =NULL) {            //iterate over the file array to get each file object             for(File file:filearray) {//determines whether the file object is a folder                if(File.isdirectory ()) {deletefolder (file); } Else{System.out.println (File.getname ()+ "---" +File.delete ()); }} System.out.println (Srcfolder.getname ()+ "---" +Srcfolder.delete ()); }    }}

Java api--Recursion

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.