递归学习资料

思路

例题

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

递归-爆栈问题

尾调用和尾递归

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

相关推荐
小成2023032026544 分钟前
Linux高级02
linux·开发语言
camellias_1 小时前
【无标题】
java·tomcat
知行合一。。。1 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y1 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
咸鱼2.01 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H1 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐1 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子1 小时前
Java:异常(exception)
java·开发语言
lifewange1 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
pluvium272 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh