java学习之路--递归
来源:互联网 发布:数控编程 过程 编辑:程序博客网 时间:2024/06/06 13:14
/** * 概念介绍: * 递归是一种方法(函数)调用自已编程技术。 * 递归就是程序设计中的数学归纳法。 * 例如: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 */ /** * 总结: * 使用非递归的方式更简洁,更易懂,运行效率更高,为什么还要用递归的算法呢。 * 递归使规模逐渐降低的方式解决问题,以这种统一的方式解决足够复杂的问题。 */
0 0
- java学习之路----递归
- java学习之路--递归
- java学习之递归
- JAVA学习之递归基础
- java学习之路(7)- 方法与递归
- java SE 学习之递归(1)
- python学习路之递归练习
- 学习lua之递归
- java学习之旅25--递归算法详解
- java学习日记_92:IO流之递归算法
- java基础学习IO流之递归 十一 -2
- Java基础之递归和方法重载学习
- java学习# 递归
- java 递归学习
- JAVA递归学习笔记
- JAVA数据结构之递归
- JAVA数据结构之递归
- java之递归调用
- Tensorflow的MNIST进阶教程CNN网络参数理解
- Line Disciplines
- 堆和栈的区别
- 首页-底部Tab导航(菜单栏)的实现:FragmentTabHost+ViewPager+Fragment
- Android Fragment使用
- java学习之路--递归
- PAT 1087
- Android获取某应用所申请的权限
- 立体匹配的研究背景以及意义
- UVALive 4730 线段树+并查集
- LeetCode:Edit Distance
- 二维数组有关数据
- Git-flow的使用
- Centos 6.5 Redis 集群部署