代码改变世界

[LeetCode]Minimum Path Sum

2014-03-14 16:06  庸男勿扰  阅读(134)  评论(0编辑  收藏  举报

原题链接:http://oj.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.

题解

  这是提到基本的动态规划题,转移方程为:dp[i][j] = min(dp[i-1][j],dp[i][j-1])+a[i][j]。

 1 class Solution {
 2 public:
 3     int minPathSum(vector<vector<int> > &grid) {
 4         int m = grid.size();
 5         int n = grid[0].size();
 6         int ret;
 7         int** dp = new int*[m];   
 8         for(int i = 0; i < m; i++)   
 9         dp[i] = new int[n];   
10 
11         dp[0][0] = grid[0][0];
12          
13         for(int i = 1; i < m; i++)
14              dp[i][0] = dp[i-1][0] + grid[i][0];
15              
16         for(int i = 1; i <n; i++)
17              dp[0][i] = dp[0][i-1] + grid[0][i];
18         
19         for(int i=1; i<m; i++){
20             for(int j=1; j<n; j++){
21                 dp[i][j] = min(dp[i][j-1],dp[i-1][j])+grid[i][j];
22             }
23         }
24         ret = dp[m-1][n-1];
25          for(int i = 0; i < m; i++)   
26              delete []dp[i];   
27         
28          delete []dp;
29         
30         return ret;
31     }
32 };
View Code