1 class Solution: 2 def __init__(self): 3 self.dp = {} 4 5 def backtrack(self,word,subword): 6 self.dp[word] = max(self.dp[word],self.dp[subword]+1) 7 for j in range(len(subword)): 8 subword2 = subword[:j] + subword[j+1:] 9 if subword2 in self.dp.keys() and self.dp[subword2] == 0: 10 self.backtrack(subword,subword2) 11 12 def longestStrChain(self, words: 'List[str]') -> int: 13 n = len(words) 14 words = sorted(words,key=lambda x:len(x)) 15 for i in range(n): 16 word = words[i] 17 self.dp[word] = 0 18 19 for word in self.dp.keys(): 20 for j in range(len(word)): 21 subword = word[:j] + word[j+1:] 22 if subword in self.dp.keys(): 23 if self.dp[subword] == 0: 24 self.backtrack(word,subword) 25 else: 26 self.dp[word] = max(self.dp[word],self.dp[subword]+1) 27 if self.dp[word] == 0: 28 self.dp[word] = 1 29 return max(self.dp.values())
本题是思路是使用动态规划,dp是一个字典,其含义是:假设以某个string作为链的结尾时形成的链的最大长度。
因此最后dp的values中,最大的值就是输入列表所能形成的最长的链的长度。