140.Word Break II

Word Break II

  Total Accepted: 30542  Total Submissions: 175073 My Submissions

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

Discuss


思路: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;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值