Advertisement
nikunjsoni

140

Jun 24th, 2021
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     unordered_map<int, vector<string>> memo;
  4.     unordered_map<string, bool> wordDict;
  5.     vector<string> wordBreak(string s, vector<string>& dict) {
  6.         memo[s.size()].push_back("");
  7.         for(auto word: dict)
  8.             wordDict[word] = true;
  9.         return solve(0, s);
  10.     }
  11.    
  12.     vector<string> solve(int i, string &s){
  13.         if(memo.count(i)) return memo[i];
  14.         for(int j=i+1; j<=s.length(); j++){
  15.             string word = s.substr(i, j-i);
  16.             if(wordDict.count(word)){
  17.                 for(string str: solve(j, s)){
  18.                     memo[i].push_back(word+(str == "" ? "" : ' '+str));
  19.                 }
  20.             }
  21.         }
  22.         return memo[i];
  23.     }
  24.    
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement