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".

word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2word_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;
}
};

最新文章

  1. lua解释执行脚本流程
  2. 用TypeScript开发爬虫程序
  3. 如何用cufflinks 拼出一个理想的注释文件
  4. &lt;转&gt;Linux环境进程间通信(二): 信号(上)
  5. Android之文字点击链接
  6. 瀑布流AJAX无刷新加载数据列表--当页面滚动到Id时再继续加载数据
  7. test、exec、match区别
  8. 【Android进阶】让程序运行效率更高的编程技巧总结
  9. 几种移动app API调用认证方案浅析
  10. c语言中的#ifdef和#ifndef
  11. FTRL(Follow The Regularized Leader)学习总结
  12. Python isinstance 方法 判断 built-in types(内置类型)技巧
  13. OpenCV 学习笔记 04 深度估计与分割
  14. python 删除文件夹
  15. Mysql数据引擎和系统库
  16. Pycharm PEP8代码编写规范 选择性忽略
  17. Redis缓存系统-Java-Jedis操作Redis,基本操作以及 实现对象保存
  18. PHP中开启gzip压缩的2种方法
  19. 涨姿势系列之——内核环境下花式获得CSRSS进程id
  20. P1757 通天之分组背包 / hdu1712 ACboy needs your help (分组背包入门)

热门文章

  1. npm安装appium server路过的坑
  2. python序列化之pickle,json,shelve
  3. 技术胖Flutter第三季-16Stack层叠布局
  4. (水题)洛谷 - P2439 - 阶梯教室设备利用 - 简单dp
  5. 201621123016 《Java程序设计》第十一周学习总结
  6. TP5之上传多张图片
  7. DP简单问题联系--最长递增子序列+最长公共子序列等
  8. CodeForces 363D 【二分+贪心】
  9. Unity3D–Texture图片空间和内存占用分析
  10. 如何快速将vc++的类转换为c#/cli