64. 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.

S: 坐标型DP

初始第一行和第一列

    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        if (m < 1) {
            return 0;
        }
        int n = grid[0].size();
        vector<vector<int>> path(m, vector<int>(n, 0));
        path[0][0] = grid[0][0];
        for (int i = 1; i < m; ++i) {
            path[i][0] = grid[i][0] + path[i-1][0];
        }
        for (int i = 1; i < n; ++i) {
            path[0][i] = grid[0][i] + path[0][i-1];
        }
        for (int i = 1; i < m; ++i) {
            for (int j = 1; j < n; ++j) {
                path[i][j] = grid[i][j] + min(path[i-1][j], path[i][j-1]);
            }
        } 
        return path[m-1][n-1];
    }

62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

S:坐标型DP

    int uniquePaths(int m, int n) {
        if(m < 1 && n < 1) {
            return 0;
        }
        vector<vector<int>> path(m, vector<int>(n, 1));
        for (int i = 1; i < m; ++i) {
            for (int j = 1; j < n; ++j) {
                path[i][j] = path[i-1][j] + path[i][j-1];
            }
        }
        return path[m-1][n-1];
    }

63. Unique Paths II

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example, There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

S: 坐标型DP

初始化第0行0列时只要有一个1,后面的位置全部不可到达,初始为0

    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        if (m < 1) {
            return 0;
        }
        int n = obstacleGrid[0].size();
        vector<vector<int>> path(m, vector<int>(n, 0));
        for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) {
            path[i][0] = 1;
        }
        for (int i = 0; i < n && obstacleGrid[0][i] == 0; ++i) {
            path[0][i] = 1;
        }
        for (int i = 1; i < m; ++i) {
            for (int j = 1; j < n; ++j) {
                if (obstacleGrid[i][j] == 0) {
                    path[i][j] = path[i-1][j] + path[i][j-1];
                }
            }
        }
        return path[m-1][n-1];
    }

results matching ""

    No results matching ""