Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.
Return the longest possible length of a word chain with words chosen from the given list of words.
Example 1:
Input: ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: one of the longest word chain is "a","ba","bda","bdca".
Note:
1 <= words.length <= 10001 <= words[i].length <= 16words[i]only consists of English lowercase letters.
-------------------------------------------------------------------------------------------
非常好的一道题目,直接想到的是DFS,假设存在n个单词,每个单词平均长度是l,那么没两个单词判断是不是前驱需要的复杂度是O(l),总体加上记忆化搜索的复杂度是O(n^2*l),当然n^2可以优化,但是优化到多少不好说,而且优化剪枝写起来非常烦躁,得根据长度进行预处理,又浪费了不少空间。
另外一种思路是从长度入手,每个词可能的前驱规模是O(l),如果某个前驱的个数知道,那么可以直接递推求最大值就好。求某个词所有前驱的复杂度是O(l^2),所以整体的复杂度是O(n*l^2),当然需要预先排序,在n>>l的情况下,显然这种思路更好,以下是代码:
class Solution:
def longestStrChain(self, words):
words.sort(key=lambda x:len(x))
dp = {}
for word in words:
dp[word] = max(dp[word[:i]+word[i+1:]]+1 if word[:i]+word[i+1:] in dp else 0 for i in range(len(word)))
return max(dp.values())
s = Solution()
print(s.longestStrChain(["a","b","ba","bca","bda","bdca"]))

本文深入探讨了在给定单词列表中寻找最长单词链的问题,通过两种不同算法的对比,详细解析了基于长度的动态规划解决方案,附带Python实现代码。
1166

被折叠的 条评论
为什么被折叠?



