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。

相关推荐
鑫鑫向栄3 小时前
[蓝桥杯]取球博弈
数据结构·c++·算法·职场和发展·蓝桥杯·动态规划
海码0071 天前
【Hot 100】70. 爬楼梯
数据结构·c++·算法·leetcode·动态规划·hot100
YGGP1 天前
动态规划之网格图模型(二)
算法·动态规划
kingmax542120082 天前
动态规划十大经典题型状态转移、模版等整理(包括leetcode、洛谷题号)
算法·leetcode·动态规划
开开心心就好2 天前
小巧实用,Windows文件夹着色软件推荐
java·开发语言·前端·决策树·c#·ocr·动态规划
编程绿豆侠2 天前
力扣HOT100之多维动态规划:62. 不同路径
算法·leetcode·动态规划
.Vcoistnt2 天前
Codeforces Round 1028 (Div. 2)(A-D)
数据结构·c++·算法·贪心算法·动态规划
一只鱼^_2 天前
力扣第452场周赛
数据结构·c++·算法·leetcode·贪心算法·动态规划·剪枝
数据皮皮侠AI2 天前
中国城市间地理距离矩阵(2024)
大数据·人工智能·线性代数·算法·矩阵·动态规划·制造
Espresso Macchiato3 天前
Leetcode 3566. Partition Array into Two Equal Product Subsets
动态规划·leetcode medium·leetcode 3566·leetcode周赛452