代码随想录训练营第三十九天|62.不同路径,63. 不同路径 II

62.不同路径

题目链接:https://leetcode.cn/problems/unique-paths/submissions/

代码:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector> dp(m+1,vector(n+1,0));
        dp[0][0] = 0;
        dp[1][1] = 0;
        for(int i = 1;i <= m; i++)
            dp[i][1] = 1;
        for(int j = 1; j <= n; j++)
            dp[1][j] = 1;
        for(int i = 2; i <= m; i ++)
        {
            for(int j = 2; j <= n; j++)
            {
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m][n];
    }
};

1.确定dp数组以及下标的含义

dp[i]: 爬到第i层楼梯,有dp[i]种方法

2.确定递推公式

dp[i][j] = dp[i-1][j] + dp[i][j-1];

3.dp数组如何初始化

注意:

首先dp[i][0]一定都是1,因为从(0, 0)的位置到(i, 0)的路径只有一条,那么dp[0][j]也同理。

4.确定遍历顺序

从递推公式dp[i] = dp[i - 1] + dp[i - 2];中可以看出,遍历顺序一定是从前向后遍历的

5.举例推导dp数组

63. 不同路径 II

题目链接:https://leetcode.cn/problems/unique-paths-ii/

代码:

class Solution {
public:
    int uniquePathsWithObstacles(vector>& obstacleGrid) {
        int m = obstacleGrid.size();    //行数
        int n = obstacleGrid[0].size();     //列数
        vector> dp(m,vector(n,0));
        dp[0][0] = 1;
        if(obstacleGrid[0][0] == 1)
            return 0;
        for(int i = 1; i < m && obstacleGrid[i][0] == 0 ; i++)
            dp[i][0] = 1;
        for(int i = 1; i < n && obstacleGrid[0][i] == 0 ; i++)
            dp[0][i] = 1;
        for(int i = 1; i < m; i++)
        {
            for(int j = 1; j < n; j++)
            {
                if(obstacleGrid[i][j-1] == 1 && obstacleGrid[i-1][j] == 1)
                    dp[i][j] = 0;
                else if(obstacleGrid[i][j-1] == 1)
                    dp[i][j] = dp[i-1][j];
                else if(obstacleGrid[i-1][j] == 1)
                    dp[i][j] = dp[i][j-1];
                else if(obstacleGrid[i][j] == 1)
                    dp[i][j] = 0;
                else
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
};

和上一道题一样

优化一下:

class Solution {
public:
    int uniquePathsWithObstacles(vector>& obstacleGrid) {
        int m = obstacleGrid.size();    //行数
        int n = obstacleGrid[0].size();     //列数
        vector> dp(m,vector(n,0));
        if(obstacleGrid[0][0] == 1)
            return 0;
        for(int i = 0; i < m && obstacleGrid[i][0] == 0 ; i++)
            dp[i][0] = 1;
        for(int i = 0; i < n && obstacleGrid[0][i] == 0 ; i++)
            dp[0][i] = 1;
        for(int i = 1; i < m; i++)
        {
            for(int j = 1; j < n; j++)
            {
                if(obstacleGrid[i][j] == 1)
                    continue;
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
};

你可能感兴趣的:(c++)