您的位置:首页 > 其它

[leetcode] 140.Word Break II

2015-09-01 14:03 441 查看
题目:

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”].

题意:

给定一个字符串,和一个词典。查看这个字符串可以由字典中的词组成。

思路:

采用动态规划加回溯。扫描到某个字符j的时候,往前查看到i,看i到j构成的字符串是否在字典中,然后看从第一个字符到第i-1个字符能否由字典中单词组成,能的话,则前j个字符可以分为两个部分,第一部分是前i个字符,第二部分是i到j这段,这两段都可以由字典种单词形成。状态转移方程如下:

if(s.substr(i, j-i) in dictionary ) && DP[i] != NULL, DP[j].push_back(i)

以上。

代码如下:

class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
if (s.empty())return vector<string>();
vector<vector<int>> DP(s.length() + 1, vector<int>());
DP[0].push_back(-1);
for (int i = 1; i <= s.length(); i++)
for (int j = 0; j < i; j++) {
if (!DP[j].empty() && wordDict.find(s.substr(j, i - j)) != wordDict.end()) {
DP[i].push_back(j);
}
}
vector<string> result;
list<string> temp;
getResult(s, result, temp, DP, s.length());
return result;
}
void getResult(string &s, vector<string>& result, list<string>& temp, vector<vector<int>>& DP, int index) {
if (index == 0) {
string res = "";
for (auto t : temp) {
if(res != "")res = res + " " + t;
else res = t;
}
result.push_back(res);
return;
}
for (auto i : DP[index]) {
temp.push_front(s.substr(i, index - i));
getResult(s, result, temp, DP, i);
temp.pop_front();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: