- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 98 lines of C++ from the credited upstream file minimum-cost-to-convert-string-iii.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 7 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int minCost(string source, string target, vector<vector<string>>& rules, vector<int>& costs) {8 static const int INF = numeric_limits<int>::max();9 10 int mx = 0;11 for (const auto& x : rules) {12 mx = max(mx, static_cast<int>(size(x[1])));13 }14 const auto& w = min(mx, static_cast<int>(size(source))) + 1;15 vector<int> dp(w, INF);16 dp[0] = 0;17 for (int i = 0; i < size(source); ++i) {18 dp[(i - 1 + w) % w] = INF;19 if (dp[i % w] == INF) {20 continue;21 }22 if (source[i] == target[i]) {23 dp[(i + 1) % w] = min(dp[(i + 1) % w], dp[i % w]);24 }25 for (int j = 0; j < size(rules); ++j) {26 if (i + size(rules[j][0]) >= size(source) + 1) {27 continue;28 }29 int c = costs[j];30 const auto& p = rules[j][0], &r = rules[j][1];31 bool ok = true;32 for (int k = 0; k < size(p); ++k) {33 if (r[k] != target[i + k]) {34 ok = false;35 break;36 }37 if (p[k] == '*') {38 ++c;39 } else if (p[k] != source[i + k]) {40 ok = false;41 break;42 }43 }44 if (ok) {45 dp[(i + size(p)) % w] = min(dp[(i + size(p)) % w], dp[i % w] + c);46 }47 }48 }49 return dp[size(source) % w] != INF ? dp[size(source) % w] : -1;50 }51};52 53 54555657class Solution2 {58public:59 int minCost(string source, string target, vector<vector<string>>& rules, vector<int>& costs) {60 static const int INF = numeric_limits<int>::max();61 62 vector<int> dp(size(source) + 1, INF);63 dp[0] = 0;64 for (int i = 0; i < size(source); ++i) {65 if (dp[i] == INF) {66 continue;67 }68 if (source[i] == target[i]) {69 dp[i + 1] = min(dp[i + 1], dp[i]);70 }71 for (int j = 0; j < size(rules); ++j) {72 if (i + size(rules[j][0]) >= size(dp)) {73 continue;74 }75 int c = costs[j];76 const auto& p = rules[j][0], &r = rules[j][1];77 bool ok = true;78 for (int k = 0; k < size(p); ++k) {79 if (r[k] != target[i + k]) {80 ok = false;81 break;82 }83 if (p[k] == '*') {84 ++c;85 } else if (p[k] != source[i + k]) {86 ok = false;87 break;88 }89 }90 if (ok) {91 dp[i + size(p)] = min(dp[i + size(p)], dp[i] + c);92 }93 }94 }95 return dp.back() != INF ? dp.back() : -1;96 }97};98