Leetcode 64. Minimum Path Sum in C [C語言] == ###### tags:`Leetcode` `DP` ## Description (medium) 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. ## Example ![](https://i.imgur.com/LHTIrrE.png) ## 怎麼解呢 因為他有限制只能往右或是往下,所以不用其他graph的算法,只要DP從左上角填表格填下去右下角就可以得到最佳解了。 所以只要看自己的左邊跟上面哪個比較小就好了。 ![](https://i.imgur.com/eW44ZCJ.jpg) ```c= int min(int a, int b){ if(a>b) return b; else return a; } int minPathSum(int** grid, int gridSize, int* gridColSize){ int i; int j; for(i=1; i<(*gridColSize); i++){ grid[0][i]=grid[0][i]+grid[0][i-1]; } for(i=1; i<gridSize; i++){ grid[i][0]=grid[i-1][0]+grid[i][0]; for(j=1; j<(*gridColSize); j++){ grid[i][j]+=min(grid[i-1][j], grid[i][j-1]); } } return grid[gridSize-1][(*gridColSize)-1]; } ``` 為了方便先把第一row處理掉,然後每個比自己的左還有上,也就是grid[i-1][j], grid[i][j-1],一路比下去就有了 Runtime: 15 ms Memory Usage: 7.4 MB Your runtime beats 70.75 % of c submissions.