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。

相关推荐
Learner__Q15 小时前
每天五分钟:动态规划-LeetCode高频题_day2
算法·leetcode·动态规划
李玮豪Jimmy1 天前
Day37:动态规划part10(300.最长递增子序列、674.最长连续递增序列 、718.最长重复子数组)
算法·动态规划
_OP_CHEN2 天前
【算法基础篇】(三十三)动态规划之区间 DP:从回文串到石子合并,吃透区间类问题的万能解法
c++·算法·蓝桥杯·动态规划·算法竞赛·acm/icpc·区间动态规划
roman_日积跬步-终至千里2 天前
【计算机设计与算法-习题2】动态规划应用:矩阵乘法与钢条切割问题
算法·矩阵·动态规划
少许极端2 天前
算法奇妙屋(十八)-子数组系列(动态规划)
算法·动态规划·子数组
_OP_CHEN3 天前
【算法基础篇】(三十二)动态规划之背包问题扩展:从多重到多维,解锁背包问题全场景
c++·算法·蓝桥杯·动态规划·背包问题·算法竞赛·acm/icpc
好易学·数据结构3 天前
可视化图解算法73:跳台阶(爬楼梯)
数据结构·算法·leetcode·动态规划·笔试
_OP_CHEN4 天前
【算法基础篇】(三十一)动态规划之基础背包问题:从 01背包到完全背包,带你吃透背包问题的核心逻辑
算法·蓝桥杯·动态规划·背包问题·01背包·完全背包·acm/icpc
啊吧怪不啊吧4 天前
算法王冠上的明珠——动态规划之路径问题(第一篇)
大数据·算法·贪心算法·动态规划
CoderYanger4 天前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节