Leetcode 983. 最低票价

1、心路历程

这道题满足最大最小问题,大概率就是用动态规划。接着,发现当days长度为1时最简单,因此递推方向一定是从n到n-1。假设n-1的问题解决了,那就研究从n-1转移到n有几种不同情况,取动作的最小值即可。

这道题自己写的有点麻烦,但是很朴素;有个技巧是按照天来递推而不是索引,这道题属于灵活转化索引与值的范畴。

2、注意的点:

1、循环的方向不要写反了

2、边界值容易搞混,要分清循环到终止点和循环到头这两种不同情况

解法一:普通动态规划

py 复制代码
class Solution:
    def mincostTickets(self, days: List[int], costs: List[int]) -> int:
        @cache
        def dp(i):  # 前i天的最低消费
            # print(i)
            if i < 0: return 0
            if i == 0: return min(costs[0], costs[1], costs[2])  # 不一定第一天最便宜
            res1 = costs[0] + dp(i - 1)
            for k1 in range(i-1, -2, -1):  # 注意遍历的顺序不要反了,注意处理边界条件
                if days[k1] <= days[i] - 7: break
            res2 = costs[1] + dp(k1)
            for k2 in range(i-1, -2, -1):
                if days[k2] <= days[i] - 30: break
            res3 = costs[2] + dp(k2)
            res = min(res1, res2, res3)
            # print(i, res, res1, res2, res3, k1)
            return res
        return dp(len(days) - 1)

解法二:精简动态规划:

py 复制代码
class Solution:
    def mincostTickets(self, days: List[int], costs: List[int]) -> int:
        lastday = days[-1]
        @cache
        def dp(day_i):
            if day_i <= 0: return 0
            if day_i not in days:  return dp(day_i - 1)  # 不在范围内就不花钱
            return min(costs[0] + dp(day_i - 1), costs[1] + dp(day_i - 7), costs[2] + dp(day_i - 30))
        return dp(lastday)
        
相关推荐
曲幽6 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶6 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..7 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵7 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf7 小时前
Python 模块与包的导入导出
前端·后端·python
8Qi87 小时前
LeetCode 213:打家劫舍 II(House Robber II)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
ice8130331818 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf8 小时前
Python venv 虚拟环境
前端·后端·python
Lsk_Smion8 小时前
力扣实训 _ [75].颜色分类 _ 杨辉三角
数据结构·算法·leetcode
林爷万福9 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪