- 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
- 40 lines of Java from the credited upstream file 3213.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 5 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.
1class Solution {2 public int minimumCost(String target, String[] words, int[] costs) {3 final int kMax = 1_000_000_000;4 final int n = target.length();5 6 int[] dp = new int[n + 1];7 Arrays.fill(dp, kMax);8 dp[0] = 0;9 10 Map<String, Integer>[] minCost = new HashMap[26];11 12 for (int i = 0; i < 26; ++i)13 minCost[i] = new HashMap<>();14 15 for (int i = 0; i < words.length; ++i) {16 final int index = words[i].charAt(0) - 'a';17 final String word = words[i];18 minCost[index].put(word, Math.min(minCost[index].getOrDefault(word, kMax), costs[i]));19 }20 21 for (int i = 0; i < n; ++i)22 for (Map.Entry<String, Integer> entry : minCost[target.charAt(i) - 'a'].entrySet()) {23 final String word = entry.getKey();24 final int cost = entry.getValue();25 final int j = i + word.length();26 if (j <= n && cost + dp[i] < dp[j] && isMatch(target, i, word))27 dp[j] = cost + dp[i];28 }29 30 return dp[n] == kMax ? -1 : dp[n];31 }32 33 private boolean isMatch(final String target, int start, final String word) {34 for (int i = 0; i < word.length(); ++i)35 if (target.charAt(start + i) != word.charAt(i))36 return false;37 return true;38 }39}40