Minimum Path Sum

来源:互联网 发布:国密sm4算法 编辑:程序博客网 时间:2024/06/08 03:09

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.


class Solution {public:int rows,cols;    int minPathSum(vector<vector<int> > &grid) {        if(!grid.size() || !grid[0].size())return 0;rows = grid.size();cols = grid[0].size();vector<vector<int> >dp;vector<int> v;for(int i = 0; i < rows; i++){v.clear();//vector二维初始化,不要像数组那样直接dp[i][j] = xx,越界,习惯!for(int j = 0; j < cols; j++)v.push_back(-1);dp.push_back(v);}return minSum(0, 0, dp, grid);    }int minSum(int r, int c, vector<vector<int> > &dp,vector<vector<int> > &grid){if(r == rows - 1 && c == cols - 1){dp[r][c] = grid[r][c];return dp[r][c];}if(dp[r][c] != -1)return dp[r][c];int rst = INT_MAX;if(c < cols - 1)rst = grid[r][c] + minSum(r, c + 1, dp, grid);if(r < rows - 1)rst = min(rst, grid[r][c] + minSum(r + 1, c, dp, grid));dp[r][c] = rst;return rst;}};


0 0
原创粉丝点击