LintCode:最小路径和

最小路径和

给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。

LintCode:最小路径和

思路一:万能的枚举

  • m行,n列的矩阵,从左上角走到右下角,需要向下移动(m-1)步,向右移动(n-1)步,共(m+n-2)步,则路径总条数为C(m+n-2, m-1)步。

  • m,n较小时可行,较大时不可行。

思路二: 动态规划

  • dp[i][j] 表示从左上到达grid[i][j]的最小值。
  • dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + a[i][j]
    • 从上面过来为dp[i-1][j] + grid[i][j]
    • 从左边过来为dp[i][j-1] + grid[i][j]
  • 初值
    • dp[0][0] = grid[0][0]
    • dp[0][j>0] = dp[0][j-1] + grid[0][j]
    • dp[i>0][0] = dp[i-1][0] + grid[i][0]
  • 复杂度:时间O(m*n), 空间O(m*n)

class Solution {
public:
    /** * @param grid: a list of lists of integers. * @return: An integer, minimizes the sum of all numbers along its path */
    int minPathSum(vector<vector<int> > &grid) {
        // write your code here
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int> > dp(m, vector<int>(n));
        for (int i=0; i<m; i++){
            for (int j=0; j<n; j++){
                if (i==0){
                    if(j==0){
                        dp[i][j] = grid[i][j];
                    }
                    else{
                        dp[i][j] = dp[i][j-1] + grid[i][j];
                    }
                }
                else if(j==0){
                    dp[i][j] = dp[i-1][j] + grid[i][j];
                }
                else{
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
                }
            }
        }
        return dp[m-1][n-1];

    }
};

dp空间优化

  • dp[i][j]只与dp[i-1][j], dp[i][j-1]有关
  • 对每个i, 正向循环j

    • 前的dp[j-1]是新的,dp[j]还是旧的
    • dp[j] = min(dp[j-1], dp[j] + a[i][j] 更新
  • 空间复杂度O(n), 时间复杂度O(m*n)


class Solution {
public:
    /** * @param grid: a list of lists of integers. * @return: An integer, minimizes the sum of all numbers along its path */
    int minPathSum(vector<vector<int> > &grid) {
        // write your code here
        int m = grid.size();
        int n = grid[0].size();
        vector<int > dp(n);
        for (int i=0; i<m; i++){
            for (int j=0; j<n; j++){
                if (i==0){
                    if(j==0){
                        dp[j] = grid[i][j];
                    }
                    else{
                        dp[j] = dp[j-1] + grid[i][j];
                    }
                }
                else if(j==0){
                    dp[j] = dp[j] + grid[i][j];
                }
                else{
                    dp[j] = min(dp[j-1], dp[j]) + grid[i][j];
                }
            }
        }
        return dp[n-1];

    }
};

参考资料

七月算法公开课 实战动态规划

你可能感兴趣的:(dp,C语言,lintcode)