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)
        
相关推荐
MeixianAgent1 小时前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6254 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB21 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵2 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田3 天前
Pydantic校验配置文件
python
hboot3 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络