码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 140 word break II 单词拆分2

时间:2019-01-28 00:36:25      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:count   ack   code   开头   rand   image   substr   info   str   

技术分享图片

 

单词拆分2,递归+dp,

需要使用递归,同时使用记忆化搜索保存下来结果,c++代码如下

 

 1 class Solution {
 2 public:
 3     //定义一个子串和子串拆分(如果有的话)的映射
 4     unordered_map<string,vector<string>>m;
 5     vector<string> wordBreak(string s, vector<string>& wordDict) {
 6         if(m.count(s)) return m[s];//当映射的子串有s说明已经判断完了返回拆分m[s]
 7         if(s.empty()) return {""};//假如s是空的返回空串
 8         vector<string> res;
 9         for(string word: wordDict){
10             if(s.substr(0,word.size())!=word) continue;//在s开头找到字典中的词;
11             vector<string> rem=wordBreak(s.substr(word.size()),wordDict);//rem是剩下的子串拆分,递归调用wordBreak
12             for(string str:rem){
13                 res.push_back(word+(str.empty() ? "" : " ")+str);//str非空时,前面加个空格后面再加单词;
14             }
15         }
16         return m[s]=res;
17     }
18 };

参考:http://www.cnblogs.com/grandyang/p/4576240.html

 

leetcode 140 word break II 单词拆分2

标签:count   ack   code   开头   rand   image   substr   info   str   

原文地址:https://www.cnblogs.com/joelwang/p/10328210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!