- 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
- 68 lines of C++ from the credited upstream file 2019.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.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int scoreOfStudents(string s, vector<int>& answers) {4 const int n = s.length() / 2 + 1;5 const unordered_map<char, function<int(int, int)>> func{6 {'+', plus<int>()}, {'*', multiplies<int>()}};7 int ans = 0;8 vector<vector<unordered_set<int>>> dp(n, vector<unordered_set<int>>(n));9 unordered_map<int, int> count;10 11 for (int i = 0; i < n; ++i)12 dp[i][i].insert(s[i * 2] - '0');13 14 for (int d = 1; d < n; ++d)15 for (int i = 0; i + d < n; ++i) {16 const int j = i + d;17 for (int k = i; k < j; ++k) {18 const char op = s[k * 2 + 1];19 for (const int a : dp[i][k])20 for (const int b : dp[k + 1][j]) {21 const int res = func.at(op)(a, b);22 if (res <= 1000)23 dp[i][j].insert(res);24 }25 }26 }27 28 const int correctAnswer = eval(s);29 30 for (const int answer : answers)31 ++count[answer];32 33 for (const auto& [answer, freq] : count)34 if (answer == correctAnswer)35 ans += 5 * freq;36 else if (dp[0][n - 1].contains(answer))37 ans += 2 * freq;38 39 return ans;40 }41 42 private:43 int eval(const string& s) {44 int ans = 0;45 int prevNum = 0;46 int currNum = 0;47 char op = '+';48 49 for (int i = 0; i < s.length(); ++i) {50 const char c = s[i];51 if (isdigit(c))52 currNum = currNum * 10 + (c - '0');53 if (!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