- 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
- 53 lines of C++ from the credited upstream file twisted-mirror-path-count.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.
123 45class Solution {6public:7 int uniquePaths(vector<vector<int>>& grid) {8 static const int MOD = 1e9 + 7;9 10 const auto& get = [&](int r, int c) {11 return size(grid) > size(grid[0]) ? grid[r][c] : grid[c][r];12 };13 14 vector<pair<int, int>> dp(min(size(grid), size(grid[0])) + 1);15 dp[1] = pair(1, 1);16 for (int r = 0; r < max(size(grid), size(grid[0])); ++r) {17 for (int c = 0; c + 1 < size(dp); ++c) {18 if (get(r, c)) {19 dp[c + 1] = pair(dp[c + 1].second, dp[c].first);20 } else {21 dp[c + 1] = pair((dp[c + 1].second + dp[c].first) % MOD,22 (dp[c + 1].second + dp[c].first) % MOD);23 }24 }25 }26 return dp.back().first;27 }28};29 30313233class Solution2 {34public:35 int uniquePaths(vector<vector<int>>& grid) {36 static const int MOD = 1e9 + 7;37 38 vector<pair<int, int>> dp(size(grid[0]) + 1);39 dp[1] = pair(1, 1);40 for (int r = 0; r < size(grid); ++r) {41 for (int c = 0; c < size(grid[0]); ++c) {42 if (grid[r][c]) {43 dp[c + 1] = pair(dp[c + 1].second, dp[c].first);44 } else {45 dp[c + 1] = pair((dp[c + 1].second + dp[c].first) % MOD,46 (dp[c + 1].second + dp[c].first) % MOD);47 }48 }49 }50 return dp.back().first;51 }52};53