您的位置:首页 > 其它

递归与尾递归

2015-08-10 22:51 591 查看
前言:

  本博客前面介绍了不少跟递归的思想相关的例子,比如“汉诺塔”,“八皇后”等。因最近又回忆起“尾递归”,故本文通过2个例子再跟大伙儿探讨一下尾递归。。。

什么是尾递归:

当递归调用是整个函数体中最后执行的语句且它的返回值不属于表达式的一部分时,这个递归调用就是尾递归。

递归实例一:

求阶乘!

package com.gdufe.recure;

import java.util.Scanner;

public class Factorial {

/**
* @param args
*/
public static void main(String[] args) {
Scanner input  = new Scanner(System.in);
System.out.println("Please input a integer below 15 to be tested:");
while(input.hasNext()){
int num = input.nextInt();
System.out.println(fac(num));
}
}
/*
* 利用数组迭代进行求解
*/
public static int fac1(int x){
int[] arr = new int[15];
arr[1]=1;
for(int i=2;i<15;i++){
arr[i] = i*arr[i-1];
}
return arr[x];
}
public static int fac2(int n){
return (n==1)?1:n*fac2(n-1);
}
/*
* 阶乘构造尾递归,进行编译优化
*/
public static int fac(int n){
return fac(n,1);
}
public static int fac(int n,int result){
if(n==1){
return result;
}else{
return fac(n-1,n*result);
}
}

}


测试输出:

Please input a integer below 15 to be tested:
3
6
11
39916800
10
3628800

递归实例二:

判断回文串!

package com.gdufe.recure;

import java.util.Scanner;

public class Palindrome {

/**
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String s = input.next();
System.out.println(s + " is a palidrome string right?"
+ isPalindrome3(s));
}
}

/*
* 构造尾递归
*/
public static boolean isPalindrome3(String str) {
return isPalindrome3(str, 0, str.length() - 1);
}

private static boolean isPalindrome3(String str, int begin, int end) {
if (begin >= end) {
return true;
} else if (str.charAt(begin) != str.charAt(end)) {
return false;
} else {
return isPalindrome3(str, begin + 1, end - 1);
}
}

public static boolean isPalindrome2(String str) {
if (str.length() <= 1) {
return true;
} else if (str.charAt(0) != str.charAt(str.length() - 1)) {
return false;
} else {
return isPalindrome2(str.substring(1, str.length() - 1));   //生成子串再重新调用!
}

}
/*
* 回文串非递归判断
*/
public static boolean isPalindrome1(String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {        //检查一半即可,不需要全部遍历
if (str.charAt(i) != str.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
}


测试输出:

aab
aab is a palidrome string right?false
bbabb
bbabb is a palidrome string right?true
000111111111000
000111111111000 is a palidrome string right?true

尾递归的意义:

  从以上尾递归的实现过程当中我们可以发现,回归过程中不用做任何操作(运算),这样的一种特性使得在执行尾递归的过程时,能够被某些特定编译器进行优化,减少内存空间的消耗。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: