左神提升6:暴力递归改动态规划

2023-11-02

内容

讲述暴力递归和动态规划的关系 =》去重的过程

记忆化搜索 傻缓存

动态规划都可以由暴力递归改进过来,解决动态规划的套路

常见的尝试模型

设计尝试过程的原则

本节是暴力递归到动态规划的总纲(很重要)

后续的课都是在讲述这一系列的套路

1、尝试=》 分辨出来所有的参数,找到所有的可变参数以及固定的值(边界)
2、可变参数的组合是什么,表大小根据可变参数的变化范围来确定
3、已知固定位置的依赖,有具体参数的例子(范围的两端)
4、知道在表中的最终想要的位置,baseCase固定的行列(确定好baseCase)
5、分析任意位置的依赖

题目一:机器人找位置

假设有排成一行的N个位置记为1~N,N一定大于或等于2
开始时机器人在其中的M位置上(M一定是1~N中的一个)
如果机器人来到1位置,那么下一步只能往右来到2位置;
如果机器人来到N位置,那么下一步只能往左来到N-1位置;
如果机器人来到中间位置,那么下一步可以往左走或者往右走;
规定机器人必须走K步,最终能来到P位置(P也是1~N中的一个)的方法有多少种
给定四个参数 N、M、K、P,返回方法数

1)cache 方法:

使用HashMap来存储当前的状态

public static void main(String[] args) {
    System.out.println(ways1(5, 2, 4, 6));
}

public static int ways1(int N, int start, int aim, int K) {
    if (N < 2 || start < 1 || start > N || aim < 1 || aim > N || K < 1) {
        return -1;
    }
    HashMap<String, Integer> cache = new HashMap<>();

    return process(start, K, aim, N, cache);
}

// 机器人还有rest步需要去走,
// 最终的目标是aim,
// 有哪些位置?1~N
public static int process(int cur, int res, int aim, int N, HashMap<String, Integer> cache) {
    String key = String.valueOf(cur) + "_" + String.valueOf(res);
    if (cache.containsKey(key)) {
        return cache.get(key);
    }
    // baseCase
    int ans = 0;
    if (res == 0) {
        ans = cur == aim ? 1 : 0;
        cache.put(key, ans);
        return ans;
    }
    // 边界情况
    if (cur == 1) {
        ans = process(cur + 1, res - 1, aim, N, cache);
        cache.put(key, ans);
        return ans;
    }
    if (cur == N) {
        ans = process(cur - 1, res - 1, aim, N, cache);
        cache.put(key, ans);
        return ans;
    }
    // 任意情况
    ans = process(cur - 1, res - 1, aim, N, cache)
            + process(cur + 1, res - 1, aim, N, cache);
    cache.put(key, ans);
    return ans;
}

2)cache化为数组

修改cache为指定大小的数组,空间复杂度降下来了

// 机器人还有rest步需要去走,
// 最终的目标是aim,
// 有哪些位置?1~N
public static int process(int cur, int res, int aim, int N, int[][] cache) {
    if (cache[cur][res] != 0 ) {
        return cache[cur][res];
    }
    // baseCase
    int ans = 0;
    if (res == 0) {
        ans = cur == aim ? 1 : 0;
        cache[cur][res] = ans;
        return ans;
    }
    // 边界情况
    if (cur == 1) {
        ans = process(cur + 1, res - 1, aim, N, cache);
        cache[cur][res] = ans;
        return ans;
    }
    if (cur == N) {
        ans = process(cur - 1, res - 1, aim, N, cache);
        cache[cur][res] = ans;
        return ans;
    }
    // 任意情况
    ans = process(cur - 1, res - 1, aim, N, cache)
            + process(cur + 1, res - 1, aim, N, cache);
    cache[cur][res] = ans;
    return ans;
}

3)继续简化

public class Test {
    public static void main(String[] args) {
        System.out.println(ways1(5, 2, 4, 6));
    }

    public static int ways1(int N, int start, int aim, int K) {
        if (N < 2 || start < 1 || start > N || aim < 1 || aim > N || K < 1) {
            return -1;
        }
        int[][] dp = new int[N + 2][K + 1];
        for (int i = 0; i <= N; i++) {
            for (int j = 0; j <= K; j++) {
                dp[i][j] = -1;
            }
        }
        return process(start, K, aim, N, dp);
    }

    // 机器人还有rest步需要去走,
    // 最终的目标是aim,
    // 有哪些位置?1~N
    public static int process(int cur, int rest, int aim, int N, int[][] dp) {
        if (dp[cur][rest] != -1) {
            return dp[cur][rest];
        }

        int ans = 0;
        if (rest == 0) {
            ans = cur == aim ? 1 : 0;
        } else if (cur == 1) {
            ans = process(2, rest - 1, aim, N, dp);
        } else if (cur == N) {
            ans = process(N - 1, rest - 1, aim, N, dp);
        } else {
            ans = process(cur - 1, rest - 1, aim, N, dp)
                    + process(cur + 1, rest - 1, aim, N, dp);
        }
        dp[cur][rest] = ans;
        return ans;
    }
}

4)dp过程

画出table表:
动态规划是直接把暴力递归的思路直接架空,拿出所对应的确定的值进行计算

在这里插入图片描述

public class Test {
    public static void main(String[] args) {
//        K:剩余步数
        System.out.println(process(2, 4, 6, 5));
    }

    // 机器人还有rest步需要去走,
    // 最终的目标是aim,
    // 有哪些位置?1~N
    public static int process(int start, int aim, int K, int N) {
        if (N < 2 || start < 1 || start > N || aim < 1 || aim > N || K < 1) {
            return -1;
        }
        int[][] dp = new int[N + 1][K + 1];

        // cur已经到aim,而剩余步数也为0了
        dp[aim][0] = 1;
//        处理其他的情况
        for (int rest = 1; rest <= K; rest++) {
            dp[1][rest] = dp[2][rest - 1];
            for (int cur = 2; cur < N; cur++) {
                dp[cur][rest] = dp[cur - 1][rest - 1] + dp[cur + 1][rest - 1];
            }
            dp[N][rest] = dp[N - 1][rest - 1];
        }

        return dp[start][K];
    }
}

题目二:抽牌博弈

给定一个整型数组arr,代表数值不同的纸牌排成一条线
玩家A和玩家B依次拿走每张纸牌
规定玩家A先拿,玩家B后拿
但是每个玩家每次只能拿走最左或最右的纸牌
玩家A和玩家B都绝顶聪明
请返回最后获胜者的分数

题解:

	// 根据规则,返回获胜者的分数
	public static int win1(int[] arr) {
		if (arr == null || arr.length == 0) {
			return 0;
		}
		int first = f1(arr, 0, arr.length - 1);
		int second = g1(arr, 0, arr.length - 1);
		return Math.max(first, second);
	}

	// arr[L..R],先手获得的最好分数返回
	public static int f1(int[] arr, int L, int R) {
		if (L == R) {
			return arr[L];
		}
		int p1 = arr[L] + g1(arr, L + 1, R);
		int p2 = arr[R] + g1(arr, L, R - 1);
		return Math.max(p1, p2);
	}

	// // arr[L..R],后手获得的最好分数返回
	public static int g1(int[] arr, int L, int R) {
		if (L == R) {
			return 0;
		}
		int p1 = f1(arr, L + 1, R); // 对手拿走了L位置的数
		int p2 = f1(arr, L, R - 1); // 对手拿走了R位置的数
		return Math.min(p1, p2);
	}

题目三:象棋问题:

暴力方法:

public class JumpHorse{
    public static void main(String[] args) {
        int enda = 5;
        int endb = 7;
        int rest = 10;
        System.out.println(process(0, 0, enda, endb, rest));
    }

    public static int process(int x, int y, int enda, int endb, int rest) {
        if (x < 0 || x > 9 || y < 0 || y > 8) {
            return 0;
        }
        if (rest == 0) {
            return x == enda && y == endb ? 1 : 0;
        }
        int res = 0;
        res = process(x+2, y+1, enda, endb, rest-1) +
                process(x+1, y+2, enda, endb, rest-1) +
                process(x-1, y-2, enda, endb, rest-1) +
                process(x-2, y-1, enda, endb, rest-1) +
                process(x-1, y+2, enda, endb, rest-1) +
                process(x+1, y-2, enda, endb, rest-1) +
                process(x+2, y-1, enda, endb, rest-1) +
                process(x-2, y+1, enda, endb, rest-1);
        return res;
    }
}

改动态规划:

public class JumpHorse{
    public static void main(String[] args) {
        int enda = 5;
        int endb = 7;
        int rest = 10;
        System.out.println(waysdp(enda, endb, rest));
    }
    public static int waysdp(int a, int b, int s) {
        int[][][] dp = new int[10][9][s + 1];
        dp[a][b][0] = 1;
        for (int step = 1; step <= s; step++) { // 按层来
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 9; j++) {
                    dp[i][j][step] = getValue(dp, i - 2, j + 1, step - 1) + getValue(dp, i - 1, j + 2, step - 1)
                            + getValue(dp, i + 1, j + 2, step - 1) + getValue(dp, i + 2, j + 1, step - 1)
                            + getValue(dp, i + 2, j - 1, step - 1) + getValue(dp, i + 1, j - 2, step - 1)
                            + getValue(dp, i - 1, j - 2, step - 1) + getValue(dp, i - 2, j - 1, step - 1);
                }
            }
        }
        return dp[0][0][s];
    }
    // 在dp表中,得到dp[i][j][step]的值,但如果(i,j)位置越界的话,返回0;
    public static int getValue(int[][][] dp, int i, int j, int step) {
        if (i < 0 || i > 9 || j < 0 || j > 8) {
            return 0;
        }
        return dp[i][j][step];
    }

}

题目四、换钱的最少货币数

暴力递归到动态规划题目。

记忆化搜索:

涉及到一些套路,dp的分析……

public class Test {
    public static void main(String[] args) {
        processOpen();
    }

    public static void processOpen() {
        int[] arr = new int[]{5, 2, 3};
        int aim = 10;
        System.out.println(process(arr, 0, aim));
    }
    
    public static int process(int[] arr, int idx, int rest) {
        if (idx >= arr.length) {
            return rest == 0 ? 1 : 0;
        }
        int sum = 0;
        for (int n = 0; n * arr[idx] <= rest; n++) {
            sum += process(arr, idx + 1, rest - n * arr[idx]);
        }
        return sum;
    }

}

dp优化

又叫做顺序依赖,DP过程

public class xx {
    public static int process(int[] arr, int idx, int aim) {
        int[][] dp = new int[arr.length + 1][aim+1];
        dp[arr.length][0] = 1;

        for (int i = arr.length-1; i >= 0; i--) {
            for (int j = 0; j <= aim; j++) {
                dp[i][j] = dp[i + 1][j];
                if (j - arr[i] >= 0) {
                    dp[i][j] += dp[i][j - arr[i]];
                }
            }
        }
        return dp[0][aim];
    }
}

如果没有枚举过程,那么就没有必要进行dp操作,如果有枚举过程,那么可以对它做优化,《斜率优化》,可以省去重复的操作时间。

空间压缩:

使用一维的数据来代替二维的数据

依赖多个数据的时候,使用两个数组交替着滚动,交替使用(省空间)

1)l-》r(背包问题)

2)范围尝试:L-R(回文)

3)2样本

尝试原则:

1)设计尽量简单,限制可变参数为整数类型,否则可能性太大了

2)可变参数个数尽量少,

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

左神提升6:暴力递归改动态规划 的相关文章

随机推荐

  • Netty编程面试题

    1 Netty 是什么 Netty是 一个异步事件驱动的网络应用程序框架 用于快速开发可维护的高性能协议服务器和客户端 Netty是基于nio的 它封装了jdk的nio 让我们使用起来更加方法灵活 2 Netty 的特点是什么 高并发 Ne
  • java数组定义错误_JAVA定义数组 int a[]=new int[100000] 错误

    我用JAVA定义了一个1W的数组可以使用 但是定义一个10W的数组提示Exceptioninthread main java lang ArrayIndexOutOfBoundsException 2147479015atJavaappli
  • php微信企业付款到银行卡获取RSA加密公钥

    微信企业付款到银行卡需要对收款方银行卡号 收款方用户名进行加密 这个过程需要获取到加密公钥 对于一些第一次接刚触到的小伙伴来说 可能比较陌生 在此记录一下自己生成 RSA公钥的过程 1 调用官方提供的接口 接口默认输出PKCS 1格式的公钥
  • 可视化库D3.js(1)-入门篇

    从今天开始可视化库 D 3 j s color red D3 js D3 js的第一章 入门篇咯 什么是D3 js D3指的是Data Dri
  • Mybatis插件原理和PageHelper结合实战分页插件

    今天和大家分享下mybatis的一个分页插件PageHelper 在讲解PageHelper之前我们需要先了解下mybatis的插件原理 PageHelper 的官方网站 https github com pagehelper Mybati
  • I/O多路复用之epoll

    关注公众号 高性能架构探索 后台回复 pdf 免费获取计算机必备经典书籍 epoll是一种事件轮询 是Linux特有的 它允许一个进程监视多个文件描述符 并在对它们进行I O操作时获取通知 它允许边缘触发和级别触发通知 在我们研究epoll
  • 跟奥巴马一起编程

    1036 跟奥巴马一起编程 15 15 point s 美国总统奥巴马不仅呼吁所有人都学习编程 甚至以身作则编写代码 成为美国历史上首位编写计算机代码的总统 2014年底 为庆祝 计算机科学教育周 正式启动 奥巴马编写了很简单的计算机代码
  • virtualbox无法创建64虚拟机的解决办法

    最近打算学习一下hadoop 需要用以虚拟机 由于vmware太大 故选择了oracle的virtualbox 结果装上virtualbox后只能创建32位的虚拟机 如下图 在网上百度了一把 说是需要 改Bioss的设置 进入securit
  • MATLAB打开.m文件乱码解决办法

    Matlab打开 m文件出现中文乱码问题 是因为Matlab存在两种编码格式 GBK和UTF 8 而不同版本的Matlab编码格式可能不统一 因此在不同版本的Matlab打开文件 由于编码格式的改变 会导致注释乱码 1 查看你的Matlab
  • 多态案例三-电脑组装

    案例描述 电脑主要组成部件为 CPU 用于计算 显卡 用于显示 内存条 用于存储 将每个零件封装出抽象基类 并且提供不同的厂商生产不同的零件 例如Intel厂商和Lenovo厂商创建电脑类提供让电脑工作的函数 并且调用每个零件工作的接口测试
  • finetune一个GPT3模型

    过程其实挺简单的 首先得注册一个账号获取token 我是叫在美国的朋友注册了一个 注册好账号后 有18美金的试用额度 基本可以完成好几次模型训练了 除了模型训练需要收费之外 大概1000个token的费用是0 02美金 设置好OPENAI
  • 浮动窗口代码(带关闭按钮+全屏漂浮)

    div div
  • Linux安装anaconda与环境变量的配置

    Linux安装anaconda的步骤 下载anaconda的安装包 后缀名为 sh 然后在root用户下执行bash XXX sh Linux配置anaconda环境变量 1 命令的路径在 usr local anaconda3 bin 2
  • 解决VM虚拟机启动后假死

    一 开机后黑屏假死 管理员cmd 输入netsh winsock reset 回车 重启系统 二 启动后假死 关闭本机防火墙
  • 数字孪生技术在各个领域得到广泛应用

    数字孪生是指将物理实体 如产品 设备 建筑 城市等 与其数字模型进行连接 通过实时数据交换和仿真模拟等技术手段 将实际的运行状态 性能 行为模式等信息反映到数字模型中 实现对其进行监测 分析 优化和预测等 实际的物理实体和数字模型之间通过感
  • 一、Docker入门

    最小安装centos7之后无法联网 无法查看ip的解决方法 cd etc sysconfig network scripts 查看目录下的文件 修改ifcfg ens33文件 ONBOOT yes 修改之后执行 service networ
  • Sprin boot 加载位置顺序

    配置文件的加载位置 Spring boot 启动会扫描一下位置的application properties或者application yml文件作为Spring boot的默认配置文件 file config 项目根目录下的config文
  • 【数据集制作】VOC2007格式数据集制作和处理教程(Faster-RCNN模型标准输入)

    说明 此次案例是制作VOC2007数据集的制作教程 用于目标检测 此次数据集处理可用于Faster RCNN YOLOv3等网络进行目标检测模型的标准输入 VOC2007数据集结构 VOC2007数据集结构如下 VOC2007 Annota
  • 灵魂拷问!GPT-4来了!人类自媒体博主存在的意义是什么?

    大家有没有想过一个问题 当某某领域大v 的文章或者视频都是GPT 4创作出来的时候 那么我们这些低产能的人类自媒体博主存在的意义又是什么呢 拿什么跟GPT 4进行竞争呢 想到这个问题是不是会有些伤感 GPT 4 VS 人类博主 首先我们先比
  • 左神提升6:暴力递归改动态规划

    内容 讲述暴力递归和动态规划的关系 去重的过程 记忆化搜索 傻缓存 动态规划都可以由暴力递归改进过来 解决动态规划的套路 常见的尝试模型 设计尝试过程的原则 本节是暴力递归到动态规划的总纲 很重要 后续的课都是在讲述这一系列的套路 1 尝试