leetcode_1048. Longest String Chain_[DP,动态规划,记忆化搜索]
Posted jasonlixuetao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode_1048. Longest String Chain_[DP,动态规划,记忆化搜索]相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/longest-string-chain/
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
.
解法:动态规划
对于任意word,任意删去其中一个字母后为word‘,若word‘在words中,则dp[word] = max(dp[word], dp[word‘] + 1)。
先将所有words按长度存储。在计算dp[word]时,先将words中长度为word.size()-1的单词放入一个set,方便word‘是否在words中。
class Solution { public: int longestStrChain(vector<string>& words) { vector<vector<string>> len_word(17, vector<string>()); for(auto word:words) len_word[word.size()].push_back(word); map<string,int> dp; int res=0; for(int i=16;i>=1;i--) { if(i<res) break; for(auto word:len_word[i]) res = max(res,dfs(len_word,word,dp)); } return res; } int dfs(vector<vector<string>>& len_word,string& nowword, map<string,int>& dp) { //cout<<nowword<<endl; if(dp.count(nowword)) return dp[nowword]; set<string> Set; for(auto word:len_word[nowword.size()-1]) Set.insert(word); int nowres=1; for(int i=0; i<nowword.size(); i++) { string temp=nowword; temp.erase(i,1); if(Set.count(temp)) nowres = max(nowres,dfs(len_word,temp,dp)+1); } return dp[nowword]=nowres; } };
以上是关于leetcode_1048. Longest String Chain_[DP,动态规划,记忆化搜索]的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode14. Longest Common Prefix
LeetCode 14. Longest Common Prefix
Leetcode_409_Longest Palindrome
LeetCode 5_Longest Palindromic Substring