Approach
Sorting and greedy selection
For Minimum Falling Path Sum II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 30 lines of C++ from the credited upstream file 1289.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 minFallingPathSum(vector<vector<int>>& grid) {4 const int n = grid.size();5 6 for (int i = 1; i < n; ++i) {7 const vector<pair<int, int>> twoMinNumAndIndexs =8 getTwoMinNumAndIndexs(grid[i - 1]);9 const auto& [firstMinNum, firstMinIndex] = twoMinNumAndIndexs[0];10 const auto& [secondMinNum, _] = twoMinNumAndIndexs[1];11 for (int j = 0; j < n; ++j)12 if (j == firstMinIndex)13 grid[i][j] += secondMinNum;14 else15 grid[i][j] += firstMinNum;16 }17 18 return ranges::min(grid.back());19 }20 21 private:22 vector<pair<int, int>> getTwoMinNumAndIndexs(const vector<int>& A) {23 vector<pair<int, int>> numAndIndexs;24 for (int i = 0; i < A.size(); ++i)25 numAndIndexs.emplace_back(A[i], i);26 ranges::sort(numAndIndexs);27 return {numAndIndexs[0], numAndIndexs[1]};28 }29};30