leetcode_1048. Longest String Chain_[DP,动态规划,记忆化搜索]
2024-09-08 08:07:18
1048. Longest String Chain
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(, vector<string>());
for(auto word:words)
len_word[word.size()].push_back(word);
map<string,int> dp;
int res=;
for(int i=;i>=;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()-])
Set.insert(word);
int nowres=;
for(int i=; i<nowword.size(); i++)
{
string temp=nowword;
temp.erase(i,);
if(Set.count(temp))
nowres = max(nowres,dfs(len_word,temp,dp)+);
}
return dp[nowword]=nowres;
}
};
最新文章
- lua解释执行脚本流程
- 用TypeScript开发爬虫程序
- 如何用cufflinks 拼出一个理想的注释文件
- <;转>;Linux环境进程间通信(二): 信号(上)
- Android之文字点击链接
- 瀑布流AJAX无刷新加载数据列表--当页面滚动到Id时再继续加载数据
- test、exec、match区别
- 【Android进阶】让程序运行效率更高的编程技巧总结
- 几种移动app API调用认证方案浅析
- c语言中的#ifdef和#ifndef
- FTRL(Follow The Regularized Leader)学习总结
- Python isinstance 方法 判断 built-in types(内置类型)技巧
- OpenCV 学习笔记 04 深度估计与分割
- python 删除文件夹
- Mysql数据引擎和系统库
- Pycharm PEP8代码编写规范 选择性忽略
- Redis缓存系统-Java-Jedis操作Redis,基本操作以及 实现对象保存
- PHP中开启gzip压缩的2种方法
- 涨姿势系列之——内核环境下花式获得CSRSS进程id
- P1757 通天之分组背包 / hdu1712 ACboy needs your help (分组背包入门)