- 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
- 74 lines of Java from the credited upstream file 2019.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 11 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 scoreOfStudents(String s, int[] answers) {3 final int n = s.length() / 2 + 1;4 int ans = 0;5 Set<Integer>[][] dp = new Set[n][n];6 Map<Integer, Integer> count = new HashMap<>();7 8 for (int i = 0; i < n; ++i)9 for (int j = i; j < n; ++j)10 dp[i][j] = new HashSet<>();11 12 for (int i = 0; i < n; ++i)13 dp[i][i].add(s.charAt(i * 2) - '0');14 15 for (int d = 1; d < n; ++d)16 for (int i = 0; i + d < n; ++i) {17 final int j = i + d;18 for (int k = i; k < j; ++k) {19 final char op = s.charAt(k * 2 + 1);20 for (final int a : dp[i][k])21 for (final int b : dp[k + 1][j]) {22 final int res = func(op, a, b);23 if (res <= 1000)24 dp[i][j].add(res);25 }26 }27 }28 29 final int correctAnswer = eval(s);30 31 for (final int answer : answers)32 count.merge(answer, 1, Integer::sum);33 34 for (final int answer : count.keySet())35 if (answer == correctAnswer)36 ans += 5 * count.get(answer);37 else if (dp[0][n - 1].contains(answer))38 ans += 2 * count.get(answer);39 40 return ans;41 }42 43 private int eval(final String s) {44 int ans = 0;45 int currNum = 0;46 int prevNum = 0;47 char op = '+';48 49 for (int i = 0; i < s.length(); ++i) {50 final char c = s.charAt(i);51 if (Character.isDigit(c))52 currNum = currNum * 10 + (c - '0');53 if (!Character.isDigit(c) || i == s.length() - 1) {54 if (op == '+') {55 ans += prevNum;56 prevNum = currNum;57 } else if (op == '*') {58 prevNum = prevNum * currNum;59 }60 op = c;61 currNum = 0;62 }63 }64 65 return ans + prevNum;66 }67 68 private int func(char op, int a, int b) {69 if (op == '+')70 return a + b;71 return a * b;72 }73}74