Leetcode 64. Minimum Path Sum

来源:互联网 发布:梦想小镇淘宝充值 编辑:程序博客网 时间:2024/06/06 06:32

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.

s思路:
1. 这样的题,会联想到用dp。能用dp的问题,一般就是,求最值问题,而且这个最值问题是可以分解的。具体说:从左上到右下的path最小,那么这条最小path上的所有点到左上之间都一定是最小Path,即:最值问题可分解的话,用dp。如:

这里写图片描述
上图所示,A->B是最小path,那么A->C,A->D,A->E都一定是最小的path。基于这样的事实,DP才能用!

//1维dp:每个点左边和上边最小值+当前点的权重!class Solution {public:    int minPathSum(vector<vector<int>>& grid) {        //        int m=grid.size();        if(m==0) return 0;        int n=grid[0].size();        //int dp[n+1]={INT_MAX};//bug:array不能初始化不为0的数,这种情况就用vector,或者memset()(c语言使用)或fill_n()(c++用),例如:        //int dp[n+1];        //fill_n(dp,n+1,INT_MAX);        vector<int> dp(n+1,INT_MAX);        dp[1]=0;//grid[0][0];        for(int i=0;i<m;i++){            for(int j=1;j<=n;j++){                dp[j]=min(dp[j-1],dp[j])+grid[i][j-1];            }            }        return dp[n];    }};
0 0