码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 64. Minimum Path Sum

时间:2017-01-09 10:54:46      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:动态   public   mini   pat   amp   span   top   tor   with   

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         vector<vector<int> > dp(m,vector<int>(n));
 7         for(int i = 0;i < m;i++){
 8             for(int j = 0;j < n ;j++){
 9                 if(i == 0){
10                     if(j == 0){//初始化
11                          dp[i][j] = grid[i][j];
12                     }
13                     else{//i==0 && j!=0
14                         dp[i][j] = dp[i][j-1]+grid[i][j];
15                     }
16                 }
17                 else if(j == 0){//i!=0&& j==0
18                     dp[i][j] = dp[i-1][j] + grid[i][j];
19                 }
20                 else{//i,j!=0
21                     dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid[i][j];
22                 }
23                 
24             }
25         }
26         return dp[m-1][n-1];
27     }
28 };

 

leetcode 64. Minimum Path Sum

标签:动态   public   mini   pat   amp   span   top   tor   with   

原文地址:http://www.cnblogs.com/LaplaceAkuir/p/6264182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!