递归及其替代算法

本文深入探讨了递归的概念,分析了其在Java和Python中的应用,并提出了在某些情况下可替代递归的算法策略,旨在优化前端开发的性能。
摘要由CSDN通过智能技术生成
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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值