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。

相关推荐
小指纹11 小时前
动态规划(一)【背包】
c++·算法·动态规划
寂空_21 小时前
【算法笔记】动态规划基础(一):dp思想、基础线性dp
c++·笔记·算法·动态规划
庐阳寒月2 天前
动态规划算法:完全背包类问题
数据结构·c++·算法·动态规划
Dream it possible!2 天前
LeetCode 热题 100_分割等和子集(89_416_中等_C++)(动态规划)
c++·leetcode·动态规划
Aqua Cheng.2 天前
代码随想录第三十七天|华为秋季笔试真题230823
java·算法·leetcode·华为·动态规划
_GR2 天前
2025年蓝桥杯第十六届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
不是仙人的闲人3 天前
算法之动态规划
数据结构·c++·算法·动态规划
callJJ3 天前
Floyd算法求解最短路径问题——从零开始的图论讲解(3)
java·算法·动态规划·图论·dijkstra算法·floyd算法·最短路径问题
谦川4 天前
蓝桥杯 蜗牛 动态规划
职场和发展·蓝桥杯·动态规划
SsummerC4 天前
【leetcode100】一和零
开发语言·python·leetcode·动态规划