Advertisement
Josif_tepe

Untitled

May 30th, 2024
636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. class Solution
  2. {
  3. public:
  4.    string s;
  5. int n;
  6. unordered_map<string, bool> exist;
  7. int dp[2222];
  8. int rec(int at) {
  9.     if(at >= s.size()) {
  10.         return 1;
  11.     }
  12.     if(dp[at] != -1) {
  13.         return dp[at];
  14.     }
  15.     int res = 0;
  16.     string tmp = "";
  17.     for(int i = at; i < s.size(); i++) {
  18.         tmp += s[i];
  19.         if(exist[tmp]) {
  20.             res = max(res, rec(at + tmp.size()));
  21.         }
  22.     }
  23.     return dp[at] = res;
  24. }
  25. int wordBreak(int n, string s, vector<string> &dictionary) {
  26.         this->n = n;
  27.         this->s = s;
  28.         for(string s : dictionary) {
  29.             exist[s] = true;
  30.         }
  31.         memset(dp, -1, sizeof dp);
  32.         return rec(0);
  33. }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement