Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
原来觉得很复杂的题,现在感觉一般般了,学习使人进步吧~~ DP,思路对了比较简单。
类似于Word Break,用sentences[i]表示i之后所有的解,则最终的解为sentences[0]。
class Solution { public: vector<string> wordBreak(string s, unordered_set<string> &dict) { int size = s.size(); if (size == 0 || dict.empty()) { return vector<string>(); } vector<vector<string>> sentences(size+1); sentences[size].push_back(""); for (int i = size - 1; i >= 0; --i) { for (int j = i; j < size; ++j) { string cur = s.substr(i, j - i + 1); if (dict.find(cur) != dict.end() && !sentences[j+1].empty()) { for (int k = 0; k < sentences[j+1].size(); ++k) { if (sentences[j+1][k].empty()) { if (j + 1 == size) { sentences[i].push_back(cur); } } else { sentences[i].push_back(cur + " " + sentences[j+1][k]); } } } } } return sentences[0]; } };
================第二次================
class Solution { public: vector<string> wordBreak(string s, unordered_set<string> &dict) { int size = s.size(); vector<vector<string>> result(size+1, vector<string>()); for (int i = size - 1; i >= 0; --i) { for (int j = i; j < size; ++j) { string word = s.substr(i, j-i+1); if (dict.find(word) != dict.end()) { if (j + 1 >= size) { result[i].push_back(word); } else { for (int k = 0; k < result[j+1].size(); ++k) { result[i].push_back(word + " " + result[j+1][k]); } } } } } return result[0]; } };