Advertisement
Guest User

Leetcode 140. Word Break II

a guest
May 10th, 2022
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<string> sentences;
  4.    
  5.     void wordBreakUtil(string s, int startIndex, vector<string> &curr,
  6.                        vector<string>& wordDict) {
  7.        
  8.         // Base case
  9.         if (startIndex == s.size()) {
  10.             string currSentence = "";
  11.            
  12.             for (auto str : curr) {
  13.                 currSentence += str + ' ';
  14.             }
  15.                
  16.             currSentence.pop_back();
  17.             sentences.emplace_back(currSentence);
  18.  
  19.             return;
  20.         }
  21.        
  22.         // Try to make a valid partition at all the indices for the current string
  23.         for (int partitionIndex = startIndex; partitionIndex < s.size(); ++partitionIndex) {
  24.             string t = s.substr(startIndex, partitionIndex - startIndex + 1);
  25.            
  26.             if (find(wordDict.begin(), wordDict.end(), t) != wordDict.end()) {
  27.                 curr.emplace_back(t);
  28.                
  29.                 wordBreakUtil(s, partitionIndex + 1, curr, wordDict);
  30.                
  31.                 curr.pop_back();
  32.             }
  33.         }
  34.     }
  35.    
  36.     vector<string> wordBreak(string s, vector<string>& wordDict) {
  37.         vector<string> curr;
  38.        
  39.         // Initially we consider the whole string 's'
  40.         int startIndex = 0;
  41.  
  42.         wordBreakUtil(s, startIndex, curr, wordDict);
  43.        
  44.         return sentences;
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement