zoukankan      html  css  js  c++  java
  • 递归

    /**
     *
     * @author Johnfung
     */
    
    
    /**
     * 概念介绍:
     * 递归是一种方法(函数)调用自已编程技术。
     * 递归就是程序设计中的数学归纳法。
     * 例如:tri(n)=1            if n=1
     *     tri(n)=n+tri(n-1)    if n>1
     * 可能while循环方法执行的速度比递归方法快,但是为什么采用递归呢。
     * 采用递归,是因为它从概念上简化了问题,而不是因为它提高效率。
     */
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    
    public class Recursion {//求三角数字的递归算法:1,3,6,10,15,21, ......
    
        static int theNumber;
    
        public static void main(String[] args) throws IOException {
            System.out.print("Enter a number: ");
            theNumber = getInt();
            //使用递归时调用,默认
            int theAnswer = triangle(theNumber);
            //使用非递归时调用
            //int theAnswer=triangle2(theNumber);
            System.out.println("Result: " + theAnswer);
        }
    
        public static int triangle(int n) {//递归方法,循环调用
            if (n == 1) {
                return 1;
            } else {
                return (n + triangle(n - 1));
            }
        }
    
        public static int triangle2(int n) {//非递归方法
            int total = 0;
            while (n > 0) {
                total = total + n--;
            }
            return total;
        }
    
        public static String getString() throws IOException {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String s = br.readLine();
            return s;
        }
    
        public static int getInt() throws IOException {
            String s = getString();
            return Integer.parseInt(s);
        }
    }
    
    /**
     * 运行结果:
     * Enter a number: 
     * 3
     * Result: 6
     */
    
    /**
     * 总结:
     * 使用非递归的方式更简洁,更易懂,运行效率更高,为什么还要用递归的算法呢。
     * 递归使规模逐渐降低的方式解决问题,以这种统一的方式解决足够复杂的问题。
     */
    
    作者:JohnFung
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    Shell脚本查看apk签名信息
    Android Studio中的六种依赖
    Gradle build设置自动log开关
    转-Android Studio系列教程六--Gradle多渠道打包
    经验分享
    Android Studio build dex jar
    iPhone6搜索如何打开?详细使用方法
    Android Studio 简单设置
    Android Studio常见问题 -- uses-sdk:minSdkVersion 8 cannot be smaller than version 9 declared in library
    iOS开发学习记录【整理】
  • 原文地址:https://www.cnblogs.com/johnfung/p/3713315.html
Copyright © 2011-2022 走看看