day28打卡

ikun1111發表於2024-10-13

62 不同路徑

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

不同路徑II

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

    }
    for(int i = 2; i <= m; ++i)
    {
        for(int j = 2; j <= n; ++j)
        {
            if(obstacleGrid[i][j] != 1)
            {
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
    }
    return dp[m][n];
}

};

相關文章