Advertisement
pb_jiang

LC943 WA

Nov 19th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. class Solution
  2. {
  3.     int check_suffix(const string &str, const string &suffix)
  4.     {
  5.         int strlen = str.size();
  6.         int sfxlen = suffix.size();
  7.         int mlen = min(strlen, sfxlen);
  8.         for (int i = mlen; i >= 0; --i) {
  9.             if (str.substr(strlen - i) == suffix.substr(0, i))
  10.                 return i;
  11.         }
  12.         return 0;
  13.     }
  14.  
  15.   public:
  16.     string shortestSuperstring(vector<string> &words)
  17.     {
  18.         int n = words.size();
  19.         // vector<string> dp(1 << n);
  20.         auto dp = vector<vector<string>>(n, vector<string>(1 << n));
  21.         // auto dp = vector<string>(1 << n);
  22.         for (int i = 0; i < n; ++i) {
  23.             dp[i][1 << i] = words[i];
  24.         }
  25.         int state = (1 << n);
  26.         string ans = "";
  27.         for (int i = 0; i < n; ++i) {
  28.             for (int s = 0; s < state; ++s) {
  29.                 if ((s & (1 << i)) == 0 || dp[i][s] == "")
  30.                     continue;
  31.                 for (int j = 0; j < n; ++j) {
  32.                     if ((s | (1 << j)) == s) {
  33.                         continue;
  34.                     }
  35.                     int ns = s | (1 << j);
  36.                     int suffix = check_suffix(dp[i][s], words[j]);
  37.                     string res = dp[i][s] + words[j].substr(suffix);
  38.                     dp[j][ns] = (dp[j][ns] == "" ? res : (res.size() < dp[j][ns].size() ? res : dp[j][ns]));
  39.                     if (ns == state - 1)
  40.                         ans = (ans == "" ? dp[j][ns] : (ans.size() < dp[j][ns].size() ? ans : dp[j][ns]));
  41.                 }
  42.             }
  43.         }
  44.         return ans;
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement