使用Sqoop从mysql导入到hive异常

Centos7 安装grafana

  返回  

动态规划 二维 64. Minimum Path Sum

2021/7/20 22:45:42 浏览:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
在这里插入图片描述

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100

用dfs写超时了

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int min = INT_MAX;
        dfs(grid,0,0,min,0);
        return min;
    }
    void dfs(vector<vector<int>>& grid, int i, int j, int &min, int sum){
        sum += grid[i][j];
        if(i == grid.size()-1 && j == grid[0].size()-1){
            min = sum < min ? sum : min;
            return; 
        }
        if(i + 1 < grid.size())
            dfs(grid,i+1,j,min,sum);
        if(j +1 < grid[0].size())
            dfs(grid,i,j+1,min,sum);
    }
};

动态规划就是记录数据的递归

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        vector<vector<int>> dp(grid.size(),vector<int>(grid[0].size(),0));
        for(int i = 0; i < grid.size(); i++){
            for(int j = 0; j < grid[0].size(); j++){
                if(i == 0 && j == 0){
                    dp[i][j] = grid[i][j];
                    continue;
                }
                else if(i - 1 >= 0 && j - 1 >= 0){
                    dp[i][j] = dp[i-1][j] < dp[i][j-1] ? dp[i-1][j] : dp[i][j-1]; 
                }
                else if(i == 0)
                    dp[i][j] = dp[i][j-1];
                else if(j == 0)
                    dp[i][j] = dp[i-1][j];

                dp[i][j] += grid[i][j];
            }
        }
        return dp[grid.size()-1][grid[0].size()-1];
    }
};

联系我们

如果您对我们的服务有兴趣,请及时和我们联系!

服务热线:18288888888
座机:18288888888
传真:
邮箱:888888@qq.com
地址:郑州市文化路红专路93号