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 row's choice must be in a column that is different from the previous row's column by at most one.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: 12 Explanation: The possible falling paths are:
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
The falling path with the smallest sum is [1,4,7]
, so the answer is 12
思路:分三種情況吧,在最左邊、最右邊和中間位置,比較與上一行的相鄰列的路徑最小位置,然後加上該位置的原始值,更新到達該位置的最短路徑長度。在最後一行選出最小的那個dp值即可。
class Solution {
public:
int minFallingPathSum(vector<vector<int>>& A) {
int n = A.size();
int dp[n][n];
//Runtime: 16 ms, faster than 57.82% of C++ online submissions for Minimum Falling Path Sum.
//Memory Usage: 9.6 MB, less than 91.90% of C++ online submissions for Minimum Falling Path Sum.
//vector<vector<int> >dp(n,vector<int>(n));
//Runtime: 12 ms, faster than 91.40% of C++ online submissions for Minimum Falling Path Sum.
//Memory Usage: 10 MB, less than 34.20% of C++ online submissions for Minimum Falling Path Sum
for(int i=0;i<n;i++) dp[0][i]=A[0][i];
for(int i=1;i<n;i++){
for(int j=0;j<n;j++){
if(j==0){
dp[i][j] = A[i][j] + min(dp[i-1][j],dp[i-1][j+1]);
}else if(j==(n-1)){
dp[i][j] = A[i][j] + min(dp[i-1][j],dp[i-1][j-1]);
}else{
dp[i][j] = A[i][j] + min(dp[i-1][j],min(dp[i-1][j-1],dp[i-1][j+1]));
}
}
}
int smallest=0x3f3f3f3f;
for(int i=0;i<n;i++){
if(smallest>dp[n-1][i])
smallest=dp[n-1][i];
}
return smallest;
}
};
有趣的是:使用 int dp[n][n]; 和 vector<vector<int> >dp(n,vector<int>(n)); 對dp初始化的時間、空間效率竟然相差這麼大!
目前還不知道究竟是何種原因,如果有知道的大佬還請說一下噢 #^_^#