代码随想录算法训练营Day40 | 62.不同路径 63. 不同路径 II
LeetCode 62.不同路径
题目链接:LeetCode 62.不同路径
思路:
二维数组dp,简单
class Solution {
public:int uniquePaths(int m, int n) {if( m==1 || n==1 ) return 1;vector<vector<int>> dp(m,vector<int>(n,0));dp[0][0] = 1;for(int i = 1; i<m; i++ ){for(int j = 1; j<n; j++ ){if(i == 1){dp[i-1][j] = 1;}if(j == 1){dp[i][j-1] = 1;}dp[i][j] = dp[i-1][j] + dp[i][j-1];}}return dp[m-1][n-1];}
};
LeetCode 63. 不同路径 II
题目链接:LeetCode 63. 不同路径 II
思路:
分4种情况,写法需要优化
class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m = obstacleGrid.size();int n = obstacleGrid[0].size();vector<vector<int>> dp(m, vector<int>(n, 0));if (obstacleGrid[0][0]) return 0;dp[0][0] = 1;for(int i=1; i<m; i++){if (obstacleGrid[i][0] == 1){for(; i<m; i++) dp[i][0] = 0;}else dp[i][0] = 1;}for(int j=1; j<n; j++){if (obstacleGrid[0][j] == 1){for(; j<n; j++) dp[0][j] = 0;}else dp[0][j] = 1;}for(int i = 1; i<m; i++){for(int j = 1; j<n; j++){if (obstacleGrid[i-1][j] == 1 && obstacleGrid[i][j-1] != 1) dp[i][j] = dp[i][j-1];else if (obstacleGrid[i][j-1] == 1 && obstacleGrid[i-1][j] != 1) dp[i][j] = dp[i-1][j];else if ((obstacleGrid[i-1][j] == 1 && obstacleGrid[i][j-1] == 1) || (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];}
};