import java.util.LinkedList;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MoveAction;
import com.sun.corba.se.spi.orbutil.fsm.State;
import com.sun.org.apache.xpath.internal.functions.Function;
/**
* 递归算法,递归的非递归替代算法
*
*/
public class TestRecursion
{
// 题目:计算给定文本内字符“a”的个数。分别用迭代和递归两种方式。
/**
* 常规算法
*/
public int countACommon(String str)
{
int count = 0;
String tmpString = str;
while (tmpString.indexOf("a") >= 0)
{
count++;
tmpString = tmpString.substring(tmpString.indexOf("a") + 1);
}
return count;
}
/**
* 递归算法
*/
public int countARecursion(String str)
{
String tmpStr = str;
if (tmpStr.indexOf("a") < 0) return 0; // 递归退出条件
else return countARecursion(tmpStr.substring(tmpStr.indexOf("a") + 1)) + 1;
}
/**
* 斐波那契数列 项,非递归(速度快,求第10000项毫无压力)
*/
public int f(int n)
{
if (n < 1) return 0;
if (n == 1) return 1;
if (n == 2) return 1;
int i, s = 0;
int s1 = 1, s2 = 1;
for (i = 3; i <= n; i++)
{
s = s1 + s2;
s2 = s1;
s1 = s;
}
递归及其替代算法
最新推荐文章于 2024-08-13 17:18:42 发布
本文深入探讨了递归的概念,分析了其在Java和Python中的应用,并提出了在某些情况下可替代递归的算法策略,旨在优化前端开发的性能。
摘要由CSDN通过智能技术生成