931. Minimum Falling Path Sum(python+cpp)
阿新 • • 發佈:2018-11-09
題目:
Given a square array of integers
A
, we want the minimum sum of a falling path throughA
.
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.
Note:
1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100
解釋:
第一反應是dfs,寫了半天dfs結果超時,程式碼如下:
class Solution(object):
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
self.result=[]
self.n=len(A)
def dfs(i,j,A,path):
if i==self.n-1:
self.result.append(sum(path))
return
else:
for k in [j-1,j,j+1]:
if k in range(self.n):
dfs(i+1,k,A,path+[A[i+1][k]])
for i in range(self.n):
dfs(0,i,A,[A[0][i]])
return min(self.result)
看到的一種騷解法,從第1行開始(index從開始),每一個值加上上一行在範圍內的([j-1:j+2])的最小的值,最後返回最後一行的最小值即可。
python騷程式碼:
class Solution(object):
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
n=len(A)
result=[[0]]
for i in range(1,n):
for j in range(n):
#j+2超出範圍也沒事,j-1超出範圍就變成-1了,會有問題
A[i][j]+=min(A[i-1][j and j-1 :j+2])
return min(A[-1])
c++程式碼:
class Solution {
public:
int minFallingPathSum(vector<vector<int>>& A) {
int n=A.size();
for (int i=1;i<n;i++)
{
for(int j=0;j<n;j++)
{
vector<int>tmp;
for(int k=j-1;k<=j+1;k++)
{
if(k>=0 && k<n)
tmp.push_back(A[i-1][k]);
}
A[i][j]+=*(std::min_element(tmp.begin(),tmp.end()));
}
}
return *min_element(A[n-1].begin(),A[n-1].end());
}
};
總結:
注意dfs的時候可以直接把和存進去,無需先把路徑存進去再遍歷求和。
學到了python and
的用法:
python中的and
從左到右計算表示式,若所有值為真,則返回最後一個值,若存在假,返回第一個假值。