Problem solution · C++

Minimum Cost to Convert String II

Minimum Cost to Convert String II: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
72 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Minimum Cost to Convert String II, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 72 lines of C++ from the credited upstream file 2977.cpp.
  • The implementation visibly relies on sequence storage, hash lookup, cached states.
  • 9 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Cost to Convert String II · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  long long minimumCost(string source, string target, vector<string>& original,                        vector<string>& changed, vector<int>& cost) {    const unordered_set<int> subLengths = getSubLengths(original);    const unordered_map<string, int> subToId = getSubToId(original, changed);    const int subCount = subToId.size();    // dist[u][v] := the minimum distance to change the substring with id u to    // the substring with id v    vector<vector<long>> dist(subCount, vector<long>(subCount, LONG_MAX));    // dp[i] := the minimum cost to change the first i letters of `source` into    // `target`, leaving the suffix untouched    vector<long> dp(source.length() + 1, LONG_MAX);     for (int i = 0; i < cost.size(); ++i) {      const int u = subToId.at(original[i]);      const int v = subToId.at(changed[i]);      dist[u][v] = min(dist[u][v], static_cast<long>(cost[i]));    }     for (int k = 0; k < subCount; ++k)      for (int i = 0; i < subCount; ++i)        if (dist[i][k] < LONG_MAX)          for (int j = 0; j < subCount; ++j)            if (dist[k][j] < LONG_MAX)              dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);     dp[0] = 0;     for (int i = 0; i < source.length(); ++i) {      if (dp[i] == LONG_MAX)        continue;      if (target[i] == source[i])        dp[i + 1] = min(dp[i + 1], dp[i]);      for (const int subLength : subLengths) {        if (i + subLength > source.length())          continue;        const string subSource = source.substr(i, subLength);        const string subTarget = target.substr(i, subLength);        if (!subToId.contains(subSource) || !subToId.contains(subTarget))          continue;        const int u = subToId.at(subSource);        const int v = subToId.at(subTarget);        if (dist[u][v] < LONG_MAX)          dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]);      }    }     return dp[source.length()] == LONG_MAX ? -1 : dp[source.length()];  }  private:  unordered_map<string, int> getSubToId(const vector<string>& original,                                        const vector<string>& changed) {    unordered_map<string, int> subToId;    for (const string& s : original)      if (!subToId.contains(s))        subToId[s] = subToId.size();    for (const string& s : changed)      if (!subToId.contains(s))        subToId[s] = subToId.size();    return subToId;  }   unordered_set<int> getSubLengths(const vector<string>& original) {    unordered_set<int> subLengths;    for (const string& s : original)      subLengths.insert(s.length());    return subLengths;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗