LeetCode_Minimun Path Sum

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.

典型的动态规划小题!

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        int rowNo = grid.size();
        if(rowNo == 0){return 0;}
        int colNo = grid[0].size();
        if (colNo == 0){
        	return 0;
        }

        std::vector <vector<int>> dp (rowNo,std::vector<int> (colNo,0));
        dp[0][0]=grid[0][0];
        for(int i=1;i<rowNo;i++){
        	dp[i][0]=dp[i-1][0]+grid[i][0];
        }
        for(int j=1;j<colNo;j++){
        	dp[0][j]=dp[0][j-1]+grid[0][j];
        }

        //start dp
        for(int i=1;i<rowNo;i++){
        	for(int j=1;j<colNo;j++){
        		if(dp[i-1][j]>dp[i][j-1]){
        			dp[i][j]=dp[i][j-1]+grid[i][j];
        		}
        		else{
        			dp[i][j]=dp[i-1][j]+grid[i][j];
        		}
        	}
        }
        return dp[rowNo-1][colNo-1];
    }
}; 


你可能感兴趣的:(LeetCode,算法)