LeetCode-62、63:Unique Paths (矩阵中独一无二的路径)

题目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?

问题解析:

在一个矩阵中,从左上角开始,每一步只能向下移动一步或者向右移动一步,到右下角停止,总共有多少种不同的路径?

链接:

思路标签:

算法:DP

数据结构:Vector

解答:

1. C++

  • 典型的动态规划题目;
  • 定义m*n的矩阵,arr[i][j]表示到达第i行第j列的位置时有多少种不同的路径;
  • 因为只能向下或者向右移动,所以很明显arr[i][j]=arr[i-1][j] + arr[i][j-1];
  • 构建二维数组即可解决,但是空间复杂度为O(m*n);
  • 简化重复子问题,我们每次只用到上一步的前一个结果和上一步的当前结果,所以用一个数组表示即可。arr[i] = arr[i] + arr[i-1]。
class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m > n)
            return uniquePaths(n, m);
        vector<int > result(m, 1);
        for(int i=1; i<n; ++i){
            for(int j=1; j<m; ++j)
                result[j] += result[j-1];
        }

        return result[m-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.

问题解析:

题目在62的基础上为网格中增加限制障碍块,有障碍的位置不能走。

链接:

思路标签:

算法:DP

数据结构:Vector

解答:

1. 使用二维数组的动态规划:

  • 与62动态规划思想是相同的
  • 不同的是因为存在障碍块,所以并不是所有的路径都能走通,所以我们将动态规划的数组全部置为0,大小为左和上各增加一行0行,以便进行计算;
  • 因为开始在起始位置,所以dp[0][1] = 1,或者dp[1][0] = 1;
  • 在有障碍块,也就是位置不为0的地方,不进行dp矩阵的计算,也就是相应位置保持为0。
  • 空间复杂度O(n*m)
class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        vector<vector <int>> dp(m+1, vector<int>(n+1, 0));
        dp[0][1] = 1;
        for(int i=1; i<=m; i++){
            for(int j=1; j<=n; j++){
                if(!obstacleGrid[i-1][j-1])
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }

        return dp[m][n];
    }
};

2. 使用一维数组的动态规划:

  • 与62动态规划思想相同的
  • 上面的解法同样存在着重复的子问题,所以我们使用一维数组进行简化;
  • 但是不同的是,我们需要在过程中判断该位置的计算是否是障碍,如果是障碍,那么此时数组该位置的值变为0,否则为上一个值加前一个当前值。
  • 空间复杂度:O(m)
class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        vector<int > dp(m+1, 0);
        dp[1] = 1;
        for(int i=1; i<=n; i++){
            for(int j=1; j<=m; j++){
                if(obstacleGrid[j-1][i-1])
                    dp[j] = 0;
                else
                    dp[j] += dp[j-1];
            }
        }

        return dp[m];
    }
};
发布了200 篇原创文章 · 获赞 740 · 访问量 69万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章