leetcode 140: Word Break II
来源:互联网 发布:网络鸡汤到底什么意思 编辑:程序博客网 时间:2024/04/28 12:55
Use DP + DFS to go through all paths. Only DFS will result in TLE.
class Solution {public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { int len=s.length(); vector<bool> dp(len,0); unordered_map<string,vector<string> > children; for(int i=0;i<len;i++) { string temp=s.substr(0,i+1); if(wordDict.find(temp)!=wordDict.end()) dp[i]=1; else { for(int j=0;j<i;j++) { if(dp[j]&&wordDict.find(s.substr(j+1,i-j))!=wordDict.end()) { dp[i]=1; break; } } } } vector<string> res; vector<string> path; dfs(s,wordDict,dp,res,path); return res; } void dfs(string s,unordered_set<string>& wordDict,vector<bool>& dp,vector<string>& res,vector<string>& path) { for(int i=s.length()-2;i>=0;i--) { if(dp[i]&&wordDict.find(s.substr(i+1))!=wordDict.end()) { path.push_back(s.substr(i+1)); dfs(s.substr(0,i+1),wordDict,dp,res,path); path.pop_back(); } } if(wordDict.find(s)!=wordDict.end()) { string temp; if(path.size()==0) temp=s; else { temp=s; for(int i=path.size()-1;i>=0;i--) temp+=' '+path[i]; } res.push_back(temp); } }};
0 0
- LeetCode: Word Break II [140]
- [leetcode 140] Word Break II
- LeetCode(140) Word Break II
- leetcode || 140、Word Break II
- leetcode 140: Word Break II
- 140 Word Break II [Leetcode]
- leetcode-140-Word Break II
- LeetCode 140 Word Break II
- LeetCode #140: Word Break II
- Leetcode 140 Word Break II
- Leetcode 140 Word Break II
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- Make GET request inside for loop
- Eclipse插件开发tomcat扩展
- 优秀博客地址
- HDOJ 1358.Period(KMP中next数组应用)
- 数独游戏java版(一)--核心算法
- leetcode 140: Word Break II
- js基础精华01
- Android上的resample处理
- js_图片放大镜
- SqlServer数据库正在还原的解决办法
- Android之CheckBox复选框控件使用inelayout.xml Xml代码
- bzoj 1036 树链剖分 迭代 模板
- cef架构
- iOS8 新特性widget开发