题目来自于:LeetCode
https://leetcode.com/problems/minimum-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.
Show Tags
Have you met this question in a real interview?
int minPathSum(int **grid, int nRows, int nCols) { if(nRows==0) return 0; int sum=0; if(nRows==1) { for(int i=0;i<nCols;++i) sum+=grid[0][i]; return sum; } if(nCols==1) { for(int i=0;i<nRows;++i) sum+=grid[i][0]; return sum; } for(int i=nRows-2;i>=0;--i) grid[i][nCols-1]+=grid[i+1][nCols-1]; for(int j=nCols-2;j>=0;--j) grid[nRows-1][j]+=grid[nRows-1][j+1]; for(int i=nRows-2;i>=0;--i) for(int j=nCols-2;j>=0;--j) { if(grid[i+1][j]<grid[i][j+1]) grid[i][j]+=grid[i+1][j]; else grid[i][j]+=grid[i][j+1]; } return grid[0][0]; }
时间: 2024-10-13 15:59:02