递归学习资料

思路

例题

css 复制代码
package 递归;

public class 反向打印字符串 {
    public static void main(String[] args) {
            f("ABC",0);
    }
    static  void f(String str,int n){
        if (n==str.length()){
            return;
        }

        f(str,n+1);

        System.out.println(str.charAt(n)+"");

    }
}

多路递归

递归优化 -剪枝(记忆优化)

时间优化但是增加了空间成本,增加了空间复杂度。

css 复制代码
package 递归;

import java.util.Arrays;

public class 记忆优化递归 {
    public static void main(String[] args) {
        System.out.printf("", fibonmacci(5));
    }
//    使用记忆法 改进
//    params:n-第n项
//    Returns:第n项的之
    public static int fibonmacci(int n){
        int [] cache = new int [n+1];
        Arrays.fill(cache,-1);//[-1,-1]
        cache[0]=0;
        cache[1]=1;
        return  f(n,cache);
    }
    public  static  int f(int n,int [] cache){
//        if (n==0) {
//            return 0;
//        }
//        if (n==1) {
//            return 1;
//        }
        if (cache[n]!=-1) {
            return cache[n];
        }
        int x=f(n-1,cache);
        int y=f(n-2,cache);
        cache [n] =x+y;//存储当前计算的值
        return x+y;
    }
}

递归-爆栈问题

尾调用和尾递归

使内存能够得到及时的释放,某些编译器可以对尾调用做优化

相关推荐
揽星河..1 小时前
【C语言】指针
c语言·开发语言
小小数媒成员2 小时前
UGUI原理(一)
开发语言·游戏·unity·游戏引擎
VIP_CQCRE2 小时前
内容自动化越跑越乱?先补上状态、去重和失败恢复
python·ai·工作流·幂等设计·内容自动化
速易达网络2 小时前
Three.js 动画入门教学:从场景搭建到流畅动效
开发语言·javascript·ecmascript
福大大架构师每日一题2 小时前
excelize v2.11.1发布:Go 1.26.0起步,16项安全修复与嵌入对象能力全面升级
开发语言·安全·golang
我喜欢就喜欢2 小时前
RAG 重排序 Rerank 实战:用 bge-reranker 把 Top-K 命中率拉回来
python·大模型·向量检索·rag·rerank
Sarvartha2 小时前
集合概述 & Collection 接口
开发语言
雪芽蓝域zzs2 小时前
第 1 章:IDEA 创建 SpringBoot3.5.16 Maven 项目
java·maven·intellij-idea
专注仿真2 小时前
卷积神经网络(CNN)算法详解
人工智能·python·算法·代码·大模型训练