- 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
- 57 lines of C++ from the credited upstream file 3539.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 4 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 magicalSum(int m, int k, vector<int>& nums) {4 const vector<vector<int>> comb = getComb(m, m);5 vector<vector<vector<vector<int>>>> mem(6 m + 1, vector<vector<vector<int>>>(7 k + 1, vector<vector<int>>(nums.size() + 1,8 vector<int>(m + 1, -1))));9 return dp(m, k, 0, 0, nums, mem, comb);10 }11 12 private:13 static constexpr int kMod = 1'000'000'007;14 15 int dp(int m, int k, int i, unsigned carry, const vector<int>& nums,16 vector<vector<vector<vector<int>>>>& mem,17 const vector<vector<int>>& comb) {18 if (m < 0 || k < 0 || (m + popcount(carry) < k))19 return 0;20 if (m == 0)21 return k == popcount(carry) ? 1 : 0;22 if (i == nums.size())23 return 0;24 if (mem[m][k][i][carry] != -1)25 return mem[m][k][i][carry];26 int res = 0;27 for (int count = 0; count <= m; ++count) {28 const long contribution = comb[m][count] * modPow(nums[i], count) % kMod;29 const int newCarry = carry + count;30 res = (res + static_cast<long>(dp(m - count, k - (newCarry % 2), i + 1,31 newCarry / 2, nums, mem, comb)) *32 contribution) %33 kMod;34 }35 return mem[m][k][i][carry] = res;36 }37 38 39 vector<vector<int>> getComb(int n, int k) {40 vector<vector<int>> comb(n + 1, vector<int>(k + 1));41 for (int i = 0; i <= n; ++i)42 comb[i][0] = 1;43 for (int i = 1; i <= n; ++i)44 for (int j = 1; j <= k; ++j)45 comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1];46 return comb;47 }48 49 long modPow(long x, long n) {50 if (n == 0)51 return 1;52 if (n % 2 == 1)53 return x * modPow(x % kMod, (n - 1)) % kMod;54 return modPow(x * x % kMod, (n / 2)) % kMod;55 }56};57