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。

相关推荐
LluckyYH14 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
ganjiee00073 天前
力扣(leetcode)每日一题 983 最低票价 |动态规划
算法·leetcode·动态规划
EQUINOX13 天前
思维+贪心,CF 1210B - Marcin and Training Camp
算法·数学建模·动态规划
_GR3 天前
每日OJ题_牛客_JOR26最长回文子串_C++_Java
java·数据结构·c++·算法·动态规划
源代码•宸4 天前
小米2025届软件开发工程师(C/C++/Java)(编程题AK)
c语言·c++·经验分享·算法·动态规划
Jcqsunny4 天前
[dp] 小信走迷宫
算法·前缀和·动态规划·dp
mengsi555 天前
最大正方形 Python题解
开发语言·python·leetcode·前缀和·动态规划·洛谷·acwing
Black—slience5 天前
LeetCode2207解题思路
java·算法·leetcode·动态规划
AnFany6 天前
数据结构编程实践20讲(Python版)—01数组
开发语言·数据结构·python·深度优先·动态规划
奶香滴小馒头7 天前
Day101 代码随想录打卡|动态规划篇--- 分割等和子集
数据结构·算法·leetcode·游戏·动态规划