码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 931. Minimum Falling Path Sum

时间:2019-01-19 11:17:29      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:mini   next   mos   column   int   return   min   solution   color   

Given a square array of integers A, we want the minimum sum of a falling path through A.
A falling path starts at any element in the first row, and chooses one element from each row.  The next rows choice must be in a column that is different from the previous rows column by at most one.

求下降路径的最小和,反向DP,从下往上遍历

 1 class Solution {
 2 public:
 3     int minFallingPathSum(vector<vector<int>>& A) {
 4         int n=A.size();
 5         int dp[110][110]={0};
 6         for(int i=0; i<n; i++){
 7             dp[n-1][i]=A[n-1][i];
 8         }
 9         for(int i=n-2; i>=0; i--){
10             dp[i][0]=A[i][0]+min(dp[i+1][0],dp[i+1][1]);
11             dp[i][n-1]=A[i][n-1]+min(dp[i+1][n-1],dp[i+1][n-2]);
12             for(int j=1; j<n-1; j++){
13                 dp[i][j]=A[i][j]+min(dp[i+1][j-1], min(dp[i+1][j], dp[i+1][j+1]));
14             }
15         }
16         int ans=0x3f3f3f3f;
17         for(int i=0; i<n; i++){
18             ans=min(ans,dp[0][i]);
19         }
20         return ans;
21     }
22 };

 

LeetCode 931. Minimum Falling Path Sum

标签:mini   next   mos   column   int   return   min   solution   color   

原文地址:https://www.cnblogs.com/Scotton-Wild/p/10290439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!