标签:
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.
求一个矩形方格,方格中填充有非负数,由方格左上角向右下角走,只能向右或者向下走,经过的方格数相加,得出的最小和是多少。
利用动态规划,我们可以将方格中的数字改为到该方格的最小和,则grid[i][j]=min{grid[i][j]+grid[i-1][j],grid[i][j]+grid[i][j-1]},其中i>0,j>0.特殊情况为:grid[0][0]不变,第一行为左边方格值+本方格值。第一列为上方方格值+本方格值。
代码如下:
<pre name="code" class="cpp">#include <iostream> #include <vector> using namespace std; int minPathSum(vector<vector<int>>& grid) ; void main() { vector<vector<int>> grid; int a[5]={1,3,1,0,2}; vector<int> temp(a,a+5); grid.push_back(temp); int b[5]={4,3,7,12,2}; vector<int> temp1(b,b+5); grid.push_back(temp1); int c[5]={9,3,1,5,2}; vector<int> temp2(c,c+5); grid.push_back(temp2); for (int i=0;i<grid.size();i++) { for (int j=0;j<5;j++) { cout<<grid[i][j]<<" "; } cout<<endl; } cout<<"The minPathSum is: "; cout<<minPathSum(grid); cout<<endl; cout<<"After minPathSum function: "<<endl; for (int i=0;i<grid.size();i++) { for (int j=0;j<5;j++) { cout<<grid[i][j]<<" "; } cout<<endl; } } int minPathSum(vector<vector<int>>& grid) { vector<int> temp; for (int i=0;i<grid.size();i++) { temp=grid[i]; for (int j=0;j<temp.size();j++) { if (i==0&&j==0) { continue; } else if (i==0&&j>0) { grid[i][j]+=grid[i][j-1]; } else if (j==0&&i>0) { grid[i][j]+=grid[i-1][j]; } else { int min; if (grid[i-1][j]>grid[i][j-1]) { min=grid[i][j-1]; } else min=grid[i-1][j]; grid[i][j]+=min; } } } return grid[grid.size()-1][temp.size()-1]; }
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45872619