- 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
- 84 lines of C++ from the credited upstream file count-no-zero-pairs-that-sum-to-n.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 16 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.
123 45class Solution {6public:7 long long countNoZeroPairs(long long n) {8 vector<vector<vector<int64_t>>> dp(2, vector<vector<int64_t>>(2, vector<int64_t>(2))); 9 dp[0][0][0] = 1;10 for (int start = 1; n; n /= 10) {11 const auto& d = n % 10;12 vector<vector<vector<int64_t>>> new_dp(2, vector<vector<int64_t>>(2, vector<int64_t>(2)));13 for (int c = 0; c < 2; ++c) {14 for (int i = 0; i < 2; ++i) {15 for (int j = 0; j < 2; ++j) {16 if (!dp[c][i][j]) {17 continue;18 }19 for (int x = start; x <= (!i ? 9 : 0); ++x) {20 for (int nc = 0; nc < 2; ++nc) {21 const auto& y = (d + nc * 10) - (c + x);22 if (!(start <= y && y <= (!j ? 9 : 0))) {23 continue;24 }25 new_dp[nc][i || !x][j || !y] += dp[c][i][j];26 }27 }28 }29 }30 }31 start = 0;32 dp = move(new_dp);33 }34 int64_t result = 0;35 for (int i = 0; i < 2; ++i) {36 for (int j = 0; j < 2; ++j) {37 result += dp[0][i][j];38 }39 }40 return result;41 }42};43 44454647class Solution2 {48public:49 long long countNoZeroPairs(long long n) {50 vector<vector<vector<int64_t>>> dp(2, vector<vector<int64_t>>(2, vector<int64_t>(2))); 51 dp[0][0][0] = 1;52 for (int start = 1; n; n /= 10) {53 const auto& d = n % 10;54 vector<vector<vector<int64_t>>> new_dp(2, vector<vector<int64_t>>(2, vector<int64_t>(2)));55 for (int c = 0; c < 2; ++c) {56 for (int i = 0; i < 2; ++i) {57 for (int j = 0; j < 2; ++j) {58 if (!dp[c][i][j]) {59 continue;60 }61 for (int x = start; x <= (!i ? 9 : 0); ++x) {62 for (int y = start; y <= (!j ? 9 : 0); ++y) {63 if ((c + x + y) % 10 != d) {64 continue;65 }66 new_dp[(c + x + y) / 10][i || !x][j || !y] += dp[c][i][j];67 }68 }69 }70 }71 }72 start = 0;73 dp = move(new_dp);74 }75 int64_t result = 0;76 for (int i = 0; i < 2; ++i) {77 for (int j = 0; j < 2; ++j) {78 result += dp[0][i][j];79 }80 }81 return result;82 }83};84