140.Word Break II
Word Break II Total Accepted: 30542 Total Submissions: 175073 Question Solution
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"]
.
Show Tags Have you met this question in a real interview? Yes No
思路:dp+回溯。dp从第一个字符开始,找到能够构成字典里面词语的起始字符,将所有这些起始字符(相对于同一个字符而言)保存成该字符的一个列表,以便最后回溯。
class Solution { public:
//dp 跟前一道题I是一样的,只不过增加了一个my_map用于记录某个字符的有效前向起始字符下标列表
void solve_dp(string &s, unordered_set<string> &dict, unordered_map<int, vector<int>> &my_map){
bool *dp = new bool[s.size()];
for (int i = 0; i<s.size(); ++i){
dp[i] = false;
}
for (int i = 0; i<s.size(); ++i){
if (i == 0 || dp[i - 1] == true){
for (auto j:dict){
if (s.find(j,i) == i){
int tem = i + j.size() - 1;
dp[tem] = true;
my_map[tem].push_back(i);
}
}
}
}
delete[]dp;
return;
}
//回溯 从最后一个字符开始有效的搜索前向起始字符
void backtrack(string &s, vector<string> &res, unordered_map<int, vector<int>> &my_map, string &one_res, int t){
if (t<0){
res.push_back(one_res);
return;
}
else{
for (int i = 0; i<my_map[t].size(); ++i){
int back;
if (one_res == ""){
//back用于返回,注意“ ”空格
one_res = s.substr(my_map[t][i], t - my_map[t][i] + 1);
back = t - my_map[t][i] + 1;
}
else {
one_res = s.substr(my_map[t][i], t - my_map[t][i] + 1) + " " + one_res;
back = t - my_map[t][i] + 2;
}
backtrack(s, res, my_map, one_res, my_map[t][i] - 1);
one_res = one_res.substr(back);
}
}
}
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> res;
if (s.size()<1) return res;
//dp,为回溯法优化
unordered_map<int, vector<int>> my_map;
solve_dp(s, dict, my_map);
//回溯法
string one_res;
backtrack(s, res, my_map, one_res, s.size() - 1);
return res;
}
};