Leetcode题解-62. Unique Paths & 63. Unique Paths II

Leetcode题解-62. Unique Paths & 63. Unique Paths II

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?
Leetcode题解-62. Unique Paths & 63. Unique Paths II_第1张图片

Above is a 3 x 7 grid. How many possible unique paths are there?

题意

一个机器人只能向右走或者向下走,求有多少条线路能够到达终点(终点为右下角的方格)

思路

这是一个组合问题,以上图为例,机器人只能向下走2次,向右走6次,所以这就是2个向下走和6个向右走的组合,C(8, 2)=28就是上图的解。在这里我们不用数学公式来计算,我们用一个二维数组来表示到达每个格子有多少种线路。到达第一行和第一列上的每个格子只有一种路线,所以先将第一行和第一列填上1,其他格子的路线数就是它左边格子的路线数加上上边格子的路线数

代码

class Solution {
public:
    int uniquePaths(int m, int n) {
        int grid[m][n];
        for(int i = 0; i < n; i++){
            grid[0][i] = 1;
        }

        for(int i = 0; i < m; i++){
            grid[i][0] = 1;
        }

        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                grid[i][j] = grid[i-1][j] + grid[i][j-1];
            }
        }
        return grid[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.

题意

在unique path的基础上,加上障碍,障碍表示对应格子不能走

思路

同unique path思路大体一样。
第一行第一列的规则:第一行如果有障碍,则障碍对应的格子和它右边的格子路线数为0,对应数组元素填0;第一列如果有障碍,则障碍对应的格子和它下边的格子路线数为0,对应数组元素填0;
其余格子的规则:如果格子是障碍,则填0,否则格子的路线数是它左边格子的路线数加上边格子的路线数

代码

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int n = obstacleGrid[0].size();
        int m = obstacleGrid.size();
        int g[m][n];
        int f = 1;
        for(int i = 0; i < n; i++){
            if(obstacleGrid[0][i] == 1) f = 0;
            g[0][i] = f;
        }
        f = 1;
        for(int i = 0; i < m; i++){
            if(obstacleGrid[i][0] == 1) f = 0;
            g[i][0] = f;
        }
        for(int i = 1; i < m; i++){
            for(int k = 1; k < n; k++){
                if(obstacleGrid[i][k] == 0)
                    g[i][k] = g[i-1][k] + g[i][k-1];
                else g[i][k] = 0;
            }
        }
        return g[m-1][n-1];
    }
};

你可能感兴趣的:(Leetcode)