2018.3.31 recursion in Java

Source: Internet
Author: User

Recursion in Java 1. Concept
    定义一个方法时,出现本方法调用本方法的过程,称之为递归
2. Features
    必然有一个边界条件    使用递归代码往往更简洁,可读性强
3. When to use recursion
n的阶乘和n的累加定义        f(n) =1      f(n)=f(n)*f(n-1)
4. Comparison of common implementations and recursive implementations
普通实现    //计算5的阶乘    public class Demo {    public static void main(String[] args) {        int sum = 1;        for (int i =5; i >=1; i--) {            sum *= i;        }        System.out.println(sum);    }}递归实现:/** *在main函数外面定义方法,不然会报错 * * 计算5的阶乘(result = 5*4*3*2*1) */public class Demo {    public static void main(String[] args) {        System.out.println(f(5));    }    public static int f(int n) {        if (1 == n){            return 1;        }else{            return n * f(n - 1);        }    }}
6. Analyze according to the three conditions of recursion
    边界条件:阶乘,乘到最后一个数,返回1,程序执行到底    递归前进段:当前的参数不等于1的时候,继续调用自身;    递归返回段:从最大的数开始乘,如果当前参数是5,那么就是5*4,即5*(5-1)即n*(n-1)
7. Example of a classical recursive algorithm----Fibonacci sequence
package com.lanqiao.demo2;/** * 斐波那契序列 *  * @author qichunlin * */public class Test {    public static void main(String[] args) {        System.out.println(f(4));        }        public static int f(int n){        if(n==1||n==2){            return 1;        }else{            return f(n-1)+f(n-2);        }    }}

2018.3.31 recursion in Java

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.