Leetcode 3213. Construct String with Minimum Cost

  • [Leetcode 3213. Construct String with Minimum Cost](#Leetcode 3213. Construct String with Minimum Cost)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的话思路上还是比较直接的,就是一个trie树加一个动态规划,通过trie树来快速寻找每一个位置作为起点时能够匹配的全部字符串,然后用一个动态规划来获取最优剪切方案。

其中,关于trie树的内容可以参考我之前的博客《经典算法:Trie树结构简介》,这里就不过多展开了。

然后当前的实现其实还蛮暴力的,时间上勉勉强强通过了全部测试样例,不过应该可以通过剪枝以及优化trie树内的内容来进行一下优化,有兴趣的读者可以考虑一下其具体实现,这里就不过多进行展开了。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Trie:
    def __init__(self):
        self.trie = {}
    
    def add_word(self, word, cost):
        trie = self.trie
        for c in word:
            trie = trie.setdefault(c, {})
        if "eos" not in trie:
            trie["eos"] = (word, cost)
        elif cost < trie["eos"][1]:
            trie["eos"] = (word, cost)
        return
    
    def find_all_prefix(self, word):
        prefixs = []
        trie = self.trie
        for c in word:
            if c not in trie:
                break
            trie = trie[c]
            if "eos" in trie:
                prefixs.append(trie["eos"])
        return prefixs

class Solution:
    def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:
        trie = Trie()
        for word, cost in zip(words, costs):
            trie.add_word(word, cost)
        n = len(target)
        ans = math.inf
        
        @lru_cache(None)
        def dp(idx):
            nonlocal ans
            if idx >= n:
                return 0
            prefixs = trie.find_all_prefix(target[idx:])
            if prefixs == []:
                return math.inf
            return min(c + dp(idx+len(w)) for w, c in prefixs)
        
        ans = dp(0)
        return ans if ans != math.inf else -1

提交代码评测得到:耗时10897ms,占用内存267.2MB。

相关推荐
放荡不羁的野指针6 小时前
leetcode150题-动态规划
算法·动态规划
水月wwww6 小时前
【算法设计】动态规划
算法·动态规划
学海一叶19 小时前
论文精读-《ReAct: Synergizing Reasoning and Acting in Language Models》,2022
论文阅读·人工智能·语言模型·动态规划·agent
leoufung2 天前
LeetCode 72. Edit Distance(编辑距离)动态规划详解
leetcode·动态规划·代理模式
无尽的罚坐人生2 天前
hot 100 42. 接雨水
数据结构·算法·leetcode·动态规划··双指针
小龙报2 天前
【算法通关指南:算法基础篇 】模拟算法专题:1. 铺地毯 2. 回文日期 3. 扫雷
c语言·数据结构·c++·算法·动态规划·知识图谱·visual studio
Dream it possible!2 天前
LeetCode 面试经典 150_Kadane_环形子数组的最大和(110_918_C++_中等)(动态规划)
c++·leetcode·面试·动态规划
少许极端2 天前
算法奇妙屋(二十二)-01背包问题(动态规划)
java·算法·动态规划·背包问题·01背包
leoufung2 天前
LeetCode 188. Best Time to Buy and Sell Stock IV - 三维DP详解
算法·leetcode·动态规划
羑悻的小杀马特2 天前
LeetCode 42接雨水全解:暴力超时→DP降维打击→双指针极限压缩空间→单调栈栈式凹槽定位,全景式解析算法优化路径
算法·leetcode·职场和发展·动态规划·双指针·单调栈·接雨水