您的位置:首页 > 其它

140. Word Break II (String; DP)

2015-10-29 06:47 351 查看
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"].

思路:需要知道从哪到哪是一个单词,所以状态选用二维数组。

class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
results.clear();
if(s.size() < 1 || wordDict.empty()) return results;

vector<vector<bool>> flag(s.length(),vector<bool>(s.length()+1, false)); //string, started from i with length j, can be found at least one form in the dict
string str;

for(int l = 1; l <= s.length();l++) //先把l小的处理完,有利于第三个for循环的判断
{
for (int i = 0; i <= s.length()-l; i++)
{
str = s.substr(i,l);
if(wordDict.find(str)!=wordDict.end()) //find one form in dict
{
flag[i][l] = true;
continue;
}

for(int k = 1; k < l; k++){ //check string started from i with length l can be divided by the words in dict
if(flag[i][k] && flag[i+k][l-k]){
flag[i][l] = true;
break;
}
}
}
}
if (!flag[0][s.length()]) {
return results;
}

string pre = "";
dfs(s,pre, flag, wordDict, 0);
return results;
}
void dfs(string &s, string pre, vector<vector<bool>> &dp, unordered_set<string> &dict, int start)
{
if(start == s.length())
{
results.push_back(pre);
return;
}
string backup = pre;
string tmp;
for(int i = 1; i <= s.length()-start;i++)
{
if(!dp[start][i]) continue;
tmp = s.substr(start, i);
if (dict.find(tmp)==dict.end()) continue;
if(pre=="") pre += tmp;
else pre = pre + " " + tmp;
dfs(s, pre, dp, dict, start+i);
pre = backup; //backtracking
}
}
private:
vector<string> results;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: