- 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
- 52 lines of Java from the credited upstream file 2901.java.
- The implementation visibly relies on sequence storage, 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 List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {3 List<String> ans = new ArrayList<>();4 5 int[] dp = new int[n];6 Arrays.fill(dp, 1);7 8 int[] prev = new int[n];9 Arrays.fill(prev, -1);10 11 for (int i = 1; i < n; ++i)12 for (int j = 0; j < i; ++j) {13 if (groups[i] == groups[j])14 continue;15 if (words[i].length() != words[j].length())16 continue;17 if (hammingDist(words[i], words[j]) != 1)18 continue;19 if (dp[i] < dp[j] + 1) {20 dp[i] = dp[j] + 1;21 prev[i] = j;22 }23 }24 25 26 int index = getMaxIndex(dp);27 while (index != -1) {28 ans.add(words[index]);29 index = prev[index];30 }31 32 Collections.reverse(ans);33 return ans;34 }35 36 private int hammingDist(final String s1, final String s2) {37 int dist = 0;38 for (int i = 0; i < s1.length(); ++i)39 if (s1.charAt(i) != s2.charAt(i))40 ++dist;41 return dist;42 }43 44 private int getMaxIndex(int[] dp) {45 int maxIndex = 0;46 for (int i = 0; i < dp.length; ++i)47 if (dp[i] > dp[maxIndex])48 maxIndex = i;49 return maxIndex;50 }51}52