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.
Hide TagsArray Dynamic Programming Find the shortest path to the top left-to-right of the matrix, and standard dynamic planning.
- Initializes the most upstream and right column of the statistical matrix.
- From top down, fill in each grid from left to right.
- Output results
1#include <iostream>2#include <vector>3 using namespacestd;4 5 6 classSolution {7 Public:8 intMinpathsum (vector<vector<int> > &grid) {9 intNrow =grid.size ();Ten if(nrow==0)return 0; One intNcol = grid[0].size (); Avector<vector<int> > cnt (nrow,vector<int> (Ncol,0)); -cnt[0][0] = grid[0][0]; - for(inti =1; i<nrow;i++) thecnt[i][0]=cnt[i-1][0]+grid[i][0]; - for(intj =1; j<ncol;j++) -cnt[0][j]=cnt[0][j-1] + grid[0][j]; - for(intI=1; i<nrow;i++){ + for(intj=1; j<ncol;j++){ -CNT[I][J] = grid[i][j] + min (cnt[i-1][j],cnt[i][j-1]); + } A } at returncnt[nrow-1][ncol-1]; - } - }; - - intMain () - { invector<vector<int> > Grid ({{1,2,3},{4,5,6},{7,8,9}}); - solution Sol; toCout<<sol.minpathsum (GRID) <<Endl; + for(intI=0; I<grid.size (); i++){ - for(intj=0; J<grid[i].size (); j + +) thecout<<grid[i][j]<<" "; *cout<<Endl; $ }Panax Notoginseng return 0; -}View Code
[Leetcode] Minimum Path Sum