LeetCode_Word Break II

在Word Break第一问的基础上,我们首先通过dp+dfs确定了整个字符串s是否可以被划分,进而要做的只需针对dp数组进行一次dfs即可,代码如下:

class Solution{
public:
  vector <string> wordBreak(string s,unordered_set <string> &dict){
    int len=s.size();
    vector <bool> dp(len+1,0);
    dp[0]=true;
    for(int i=1;i<=len;i++){
      //check if s[0,..,i] can be Broken
      string subStr=s.substr(0,i);
      for(int j=0;j<i;j++){
        dp[i] = dp[j]&&dictContain(subStr,dict);
        if(dp[i]) break;
        subStr.erase(subStr.begin());
      }
    }

    //s can't be broken
    if(!dp[len]) return result;
    
    dfs(s,s,dict,dp,0,0);
    return result;
  }
  bool dictContain(string s,const unordered_set <string> &dict){
    auto iter=dict.find(s);
    if(iter!=dict.end()){
      return true;
    }
    return false;
  }
  void dfs(const string &s,string breStr,const unordered_set <string> &dict,
          const vector <bool> &dp,int pos,int brePos){
       for(int i=1;i+pos<=s.size();i++){
         if(dp[pos+i]&&dictContain(s.substr(pos,i),dict)){
           if(i==s.size()-pos){
             result.push_back(breStr);
           }
           else{
             auto iter=breStr.begin()+i+brePos;
             breStr.insert(iter,' ');
             dfs(s,breStr,dict,dp,pos+i,brePos+i+1);
             iter=breStr.begin()+i+brePos;
             breStr.erase(iter);
           }
         }
       }     
  }
private:
  vector <string> result;
};


你可能感兴趣的:(LeetCode)