您的位置:首页 > 其它

LeetCode 140. Word Break II

2016-04-24 08:57 471 查看
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"]
.

// I currently only do it using backtracking. But this has high complexity..... need to think about how to do it using DP.

void wordBreak(string s, int pos, vector< vector<string > >& res, vector<string>& path, unordered_set<string>& wordDict) {
if(pos == s.size()) {
res.push_back(path);
return;
}
for(int i = pos; i < s.size(); ++i) {
string tmp = s.substr(pos, i - pos + 1);
if(wordDict.find(tmp) != wordDict.end()) {
path.push_back(tmp);
wordBreak(s, i + 1, res, path, wordDict);
path.pop_back();
}
}
}

vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector< vector<string> > res;
vector<string> path;
wordBreak(s, 0, res, path, wordDict);
vector<string> result;
for(int i = 0; i < res.size(); ++i) {
string tmp = "";
for(int j = 0; j < res[i].size(); ++j) {
tmp = tmp + " " + res[i][j];
}
result.push_back(tmp);
}
return result;
}

// test
int main(void) {
string test = "aaaaa";
unordered_set<string> wordDict{"a", "aaa", "aa", "aaaaa", "aaaa"};

vector<string> res = wordBreak(test, wordDict);
for(auto iter : res) {
cout << iter << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: