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。

相关推荐
Bi_BIT2 小时前
代码随想录训练营打卡Day38| 动态规划part06
算法·动态规划
利刃大大6 小时前
【动态规划:01背包】01背包详解 && 模板题 && 优化
c++·算法·动态规划·力扣·背包问题
Miraitowa_cheems1 天前
LeetCode算法日记 - Day 94: 最长的斐波那契子序列的长度
java·数据结构·算法·leetcode·深度优先·动态规划
不染尘.1 天前
2025_11_5_刷题
开发语言·c++·vscode·算法·贪心算法·动态规划
Jasmine_llq4 天前
《P6772 [NOI2020] 美食家》
动态规划·状态压缩·矩阵快速幂·事件排序与分段处理·图论基础(图的表示与遍历)
mifengxing5 天前
力扣每日一题——接雨水
c语言·数据结构·算法·leetcode·动态规划·
贝塔实验室6 天前
LDPC 码的构造方法
算法·fpga开发·硬件工程·动态规划·信息与通信·信号处理·基带工程
ゞ 正在缓冲99%…6 天前
leetcode1312.让字符串成为回文串的最少插入次数
数据结构·算法·leetcode·动态规划·记忆化搜索
Miraitowa_cheems8 天前
LeetCode算法日记 - Day 88: 环绕字符串中唯一的子字符串
java·数据结构·算法·leetcode·深度优先·动态规划
焜昱错眩..8 天前
代码随想录第四十八天|1143.最长公共子序列 1035.不相交的线 53. 最大子序和 392.判断子序列
算法·动态规划