# 1289. Minimum Falling Path Sum II

Given an `n x n` integer matrix `grid`, return  the minimum sum of a falling path with non-zero shifts.

A falling path with non-zero shifts is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.

Example 1:

``````Input: arr = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.
``````

Example 2:

``````Input: grid = [[7]]
Output: 7
``````

Constraints:

• `n == grid.length == grid[i].length`
• `1 <= n <= 200`
• `-99 <= grid[i][j] <= 99`

``````class Solution {
public:
int minFallingPathSum(vector<vector<int>>& grid) {
int n = grid.size(), res = INT_MAX;
vector<vector<int>> dp(n, vector<int>(n));
dp[0] = grid[0];
for (int i = 1; i < n; ++i) {
for (int j = 0; j < n; ++j) {
dp[i][j] = INT_MAX;
for (int k = 0; k < n; ++k) {
if (k != j) dp[i][j] = min(dp[i][j], grid[i][j] + dp[i - 1][k]);
}
}
}
return *min_element(dp[n - 1].begin(), dp[n - 1].end());
}
};
``````

``````class Solution {
public:
int minFallingPathSum(vector<vector<int>>& grid) {
int n = grid.size(), res = INT_MAX;
vector<int> dp = grid[0];
for (int i = 0; i < n - 1; ++i) {
int mn = INT_MAX, idx = -1, sm = INT_MAX;
for (int j = 0; j < n; ++j) {
if (dp[j] < mn) {
sm = mn;
mn = dp[j];
idx = j;
} else if (dp[j] < sm) {
sm = dp[j];
}
}
for (int j = 0; j < n; ++j) {
dp[j] = grid[i + 1][j] + (j == idx ? sm : mn);
}
}
return *min_element(dp.begin(), dp.end());
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1289

Minimum Falling Path Sum

Paint House II

https://leetcode.com/problems/minimum-falling-path-sum-ii/

https://leetcode.com/problems/minimum-falling-path-sum-ii/discuss/689243/Java-Simple-DP

https://leetcode.com/problems/minimum-falling-path-sum-ii/discuss/452207/C%2B%2B-O(nm)-or-O(1)

https://leetcode.com/problems/minimum-falling-path-sum-ii/discuss/723719/C%2B%2B-easy-DP-O(N*N)

LeetCode All in One 题目讲解汇总(持续更新中…)

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation