- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 31 lines of C++ from the credited upstream file 3546.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 bool canPartitionGrid(vector<vector<int>>& grid) {4 const long totalSum = accumulate(grid.begin(), grid.end(), 0L,5 [](long acc, const vector<int>& row) {6 return acc + accumulate(row.begin(), row.end(), 0L);7 });8 return canPartition(grid, totalSum) ||9 canPartition(transposed(grid), totalSum);10 }11 12 private:13 bool canPartition(const vector<vector<int>>& lines, long totalSum) {14 long runningSum = 0;15 for (const vector<int>& line : lines) {16 runningSum += accumulate(line.begin(), line.end(), 0L);17 if (runningSum * 2 == totalSum)18 return true;19 }20 return false;21 }22 23 vector<vector<int>> transposed(const vector<vector<int>>& grid) {24 vector<vector<int>> res(grid[0].size(), vector<int>(grid.size()));25 for (int i = 0; i < grid.size(); ++i)26 for (int j = 0; j < grid[0].size(); ++j)27 res[j][i] = grid[i][j];28 return res;29 }30};31