931. Minimum Falling Path Sum(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83867558

题目:

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.

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从左到右计算表达式,若所有值为真,则返回最后一个值,若存在假,返回第一个假值。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83867558