LeetCode ||& Word Break && Word Break II(转)——动态规划

时间:2021-11-28 10:50:41

一、

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s ="leetcode",
dict =["leet", "code"].

Return true because"leetcode"can be segmented as"leet code".

 class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int len=s.length();
vector<bool> v(len+,false);
v[]=true;
for(int pos=;pos<len;pos++){
for(int i=pos;v[pos]&&i<len;i++){
if(dict.find(s.substr(pos,i-pos+))!=dict.end())
v[i+]=true;
}
}
return v[len];
}
};

二、

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

即不仅要确定字符串是否能被字典分割,还要找出所有可能的组合。参考word break那题的DP思路,首先,从尾部开始逆向看字符串 s ,循环截取一个存在的词(milestone 1),然后在截取的位置递归,继续向前看,继续截取。。。知道到达头部,此时组合出一种答案;然后进入milestone 1 处的下一次循环,如下图的milestone 1,截取另外一个词,找另外一个答案。。。

LeetCode ||& Word Break && Word Break II(转)——动态规划

代码如下:

  1.  class Solution {
    vector<string> midres;
    vector<string> res;
    vector<bool> *dp;
    public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
    int len = s.length(); dp = new vector<bool>[len];
    for(int i=; i<len; ++i){
    for(int j=i; j<len; ++j){
    if(dict.find(s.substr(i, j-i+))!=dict.end()){
    dp[i].push_back(true); //第二维的下标实际是:单词长度-1
    }else{
    dp[i].push_back(false); //数组第二维用vector,size不一定是n,这样比n*n节省空间
    }
    }
    }
    func(s, len-);
    return res;
    } void func(const string &s, int i){
    if(i>=){
    for(int j=; j<=i; ++j){ if(dp[j][i-j]){ //注意此处的第二个下标是 i-j,不是i,因为数组的第二维长度是不固定的,第二维的下标实际是单词长度-1 midres.push_back(s.substr(j, i-j+));
    func(s, j-);
    midres.pop_back(); //继续考虑for循环的下一个分段处
    }
    }
    return;
    }
    else{
    string str;
    for(int k=midres.size()-; k>=; --k){ //注意遍历的顺序是倒序的
    str += midres[k]; //注意此处是k,不是i
    if(k>)
    str += " ";
    }
    res.push_back(str);
    return;
    }
    }
    };

注意递归函数的技巧,用全局变量res来保存答案,每次递归成功到达头部时将此中间结果保存到res。

转自:http://blog.csdn.net/jiadebin890724/article/details/34829865