当前位置: 首页 > news >正文

Leetcode983. 最低票价

Every day a Leetcode

题目来源:983. 最低票价

解法1:记忆化搜索

定义 dfs(i) 表示 1 到 i 天的最小花费。

如果第 i 天不在 days 中,那么问题变成 1 到 i−1 天的最小花费,即:dfs(i)=dfs(i−1)。

如果第 i 天在 days 中,分类讨论:

  • 在第 i 天购买为期 1 天的通行证,接下来需要解决的问题为:1 到 i−1 天的最小花费,即 dfs(i)=dfs(i−1)+costs[0]。
    在第 i−6 天购买为期 7 天的通行证,接下来需要解决的问题为:1 到 i−7 天的最小花费,即 dfs(i)=dfs(i−7)+costs[1]。
    在第 i−29 天购买为期 30 天的通行证,接下来需要解决的问题为:1 到 i−30 天的最小花费,即 dfs(i)=dfs(i−30)+costs[2]。

这三种情况取最小值,就得到了 dfs(i)。

代码:

#
# @lc app=leetcode.cn id=983 lang=python3
#
# [983] 最低票价
## @lc code=start
class Solution:def mincostTickets(self, days: List[int], costs: List[int]) -> int:hashSet = set(days)@cachedef dfs(i: int) -> int:if i <= 0:return 0if i not in hashSet:return dfs(i - 1)return min(dfs(i - 1) + costs[0], dfs(i - 7) + costs[1], dfs(i - 30) + costs[2])return dfs(days[-1])      
# @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(D),其中 D=days[n−1],n 为数组 days 的长度。

空间复杂度:O(D),其中 D=days[n−1],n 为数组 days 的长度。

解法2:动态规划

代码:

/** @lc app=leetcode.cn id=983 lang=cpp** [983] 最低票价*/// @lc code=start
class Solution
{
public:int mincostTickets(vector<int> &days, vector<int> &costs){int lastDay = days[days.size() - 1];vector<int> dp(lastDay + 1);unordered_set<int> hashSet(days.begin(), days.end());// 初始化dp[0] = 0;// 状态转移for (int i = 1; i <= lastDay; i++){if (!hashSet.contains(i))dp[i] = dp[i - 1];elsedp[i] = min({dp[i - 1] + costs[0],dp[max(i - 7, 0)] + costs[1],dp[max(i - 30, 0)] + costs[2]});}return dp[lastDay];}
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(D),其中 D=days[n−1],n 为数组 days 的长度。

空间复杂度:O(D),其中 D=days[n−1],n 为数组 days 的长度。


http://www.mrgr.cn/news/40521.html

相关文章:

  • psutil库的使用说明
  • harproxy
  • 【人活着的意义第三弹】一个研发团队每个角色的定位和作用
  • [uni-app]小兔鲜-05登录+个人中心
  • 数据交易和算力共享(特别是大模型训练算力)之间的相互促进关系
  • 编码风格之(6)C++语言规范(Google风格)(1)
  • iPhone使用技巧:如何恢复变砖的 iPhone 或 iPad
  • 网络数据安全管理条例中涉及企业报告的义务汇总
  • 风速预测(五)基于Pytorch的EMD-CNN-LSTM模型
  • web开发(1)-基础
  • 躺平成长:微信小程序运营日记第二天
  • 网关的作用及其高可用性设计详解
  • DBeaver详细安装与使用教程-免费的数据库管理工具
  • RAG(Retrieval Augmented Generation)及衍生框架:CRAG、Self-RAG与HyDe的深入探讨
  • 基于SpringBoot+Vue的留学信息推荐系统
  • 【人活着的意义第二弹】我的主体性和客体分离的理解
  • 优化理论及应用精解【13】
  • 【智能算法应用】正余弦优化算法求解二维路径规划问题
  • Vue2(十三):路由
  • 各种图形的打印