递归学习资料

思路

例题

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;
    }
}

递归-爆栈问题

尾调用和尾递归

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

相关推荐
用户8307196840821 小时前
Spring Boot WebClient性能比RestTemplate高?看完秒懂!
java·spring boot
Assby3 小时前
从洋葱模型看Java与Go的设计哲学:为什么它们如此不同?
java·后端·架构
会员源码网3 小时前
Python中生成器函数与普通函数的区别
python
Java水解3 小时前
Python开发从入门到精通:Web框架Django实战
后端·python
belhomme4 小时前
(面试题)Netty 线程模型
java·面试·netty
曲幽5 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
Lupino8 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
NE_STOP8 小时前
MyBatis-plus进阶之映射与条件构造器
java
Flittly9 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent