Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[] Solution:
  方法一,使用递归:【通不过牛客的例子】
 class Solution {
public:
unordered_map<string, vector<string>>map;
vector<string> wordBreak(string s, unordered_set<string> &dict) {
if (map.find(s) != map.end())return map[s];
if (s.empty())return { "" };
vector<string>res;
for (auto word : dict)
{
if (s.substr(, word.size()) != word)continue;
vector<string>rem = wordBreak(s.substr(word.size()), dict);
for (auto str : rem)
res.push_back(word + (str.empty() ? "" : " ") + str);
}
return map[s] = res;
}
};

  方法二:使用动态规划
 //使用动态规划

 class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
int len = s.length();
dp = new vector<bool>[len];
for (int pos = ; pos < len; pos++) {
for (int i = ; i < len - pos + ; i++) {
if (dict.find(s.substr(pos, i)) != dict.end())
dp[pos].push_back(true);
else
dp[pos].push_back(false);
}
}
dfs(s, len - );
return res;
}
void dfs(string s, int n) {
if (n >= ) {
for (int i = n; i >= ; i--) {
if (dp[i][n - i]) {
mid.push_back(s.substr(i, n - i + ));
dfs(s, i - );
mid.pop_back();
}
}
}
else {
string r;
for (int j = mid.size() - ; j >= ; j--) {
r += mid[j];
if (j > )
r += " ";
}
res.push_back(r);
}
}
vector<bool> *dp;
vector<string> res;
vector<string> mid;
};
												

最新文章

  1. .net core 学习笔记(1)-分页控件的使用
  2. Android中editText使用报错
  3. mac os 体验
  4. SSH入门简单搭建例子
  5. iOS Json转换模型库:YYModel
  6. vim查找/替换字符串
  7. js命名空间笔记
  8. Activity和Servlet的相似之处和区别
  9. Entity Framework技巧系列之八 - Tip 29 – 34
  10. js中checkbox的全选和反选的实现
  11. 面试之路(16)-归并排序详解(MergeSort)递归和非递归实现
  12. Java关于读取Excel文件~xlsx xls csv txt 格式文件~持续汇总~
  13. Android 开发工具类 19_NetworkStateReceiver
  14. MySQL内部执行流程
  15. was监控脚本编写时的注意点
  16. eclipse maven 导出项目依赖的jar包
  17. MySQL Master High Available 源码篇
  18. 树莓派3B+首次登陆通过网络
  19. c++泛型模板
  20. Java多线程(三) —— 线程并发库之总体架构

热门文章

  1. 让Tomcat支持php
  2. 通过TCP/IP连接Mysql数据库
  3. python3+django2 个人简单博客实现 -正在施工
  4. STL中的查找
  5. __attribute__ ((packed))字节对齐
  6. python3 requests库学习笔记(MOOC网)
  7. JavaScript — event介绍以及兼容处理
  8. PHP 与Python 读取大文件的区别
  9. PHP 遍历数组for foreach while
  10. 前端学习(二十二)css3(笔记)