zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Hide Tags
     Array Dynamic Programming
     
         找矩阵左上到右下的最短路径,标准的动态规划。
    1. 初始化统计矩阵的最上行,最右列。
    2. 从上往下,从左到右填写每格。
    3. 输出结果
     1 #include <iostream>
     2 #include <vector>
     3 using namespace std;
     4 
     5 
     6 class Solution {
     7 public:
     8     int minPathSum(vector<vector<int> > &grid) {
     9         int nrow = grid.size();
    10         if(nrow==0) return 0;
    11         int ncol = grid[0].size();
    12         vector<vector<int> > cnt(nrow,vector<int>(ncol,0));
    13         cnt[0][0] = grid[0][0];
    14         for(int i =1;i<nrow;i++)
    15             cnt[i][0]=cnt[i-1][0]+grid[i][0];
    16         for(int j = 1;j<ncol;j++)
    17             cnt[0][j]=cnt[0][j-1] + grid[0][j];
    18         for(int i=1;i<nrow;i++){
    19             for(int j=1;j<ncol;j++){
    20                 cnt[i][j] = grid[i][j] + min(cnt[i-1][j],cnt[i][j-1]);
    21             }
    22         }
    23         return cnt[nrow-1][ncol-1];
    24     }
    25 };
    26 
    27 int main()
    28 {
    29     vector<vector<int> > grid({{1,2,3},{4,5,6},{7,8,9}});
    30     Solution sol;
    31     cout<<sol.minPathSum(grid)<<endl;
    32     for(int i=0;i<grid.size();i++){
    33         for(int j=0;j<grid[i].size();j++)
    34             cout<<grid[i][j]<<" ";
    35         cout<<endl;
    36     }
    37     return 0;
    38 }
    View Code
  • 相关阅读:
    正则表达式
    字节流和字符流小练习
    File汇总
    java一不容易就容易错的知识点汇总
    a++和++a区别
    线程安全的3种方式
    bs4和css选择器的基本使用
    清点作业情况
    cookie和session的使用
    用post请求制作翻译
  • 原文地址:https://www.cnblogs.com/Azhu/p/4153903.html
Copyright © 2011-2022 走看看