62. Unique Paths
class Solution {
public:
int uniquePaths(int m, int n) {
if(m <= || n <= )
return ;
vector<vector<int> > dp(m,vector<int>(n));
dp[][] = ;
for(int i = ;i < m;i++)
dp[i][] = ;
for(int i = ;i < n;i++)
dp[][i] = ;
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
dp[i][j] = dp[i-][j] + dp[i][j-];
}
}
return dp[m - ][n - ];
}
};
63. Unique Paths II
leetcode的例子中int会越界,所以需要用long
与Unique Paths I不同在于多了障碍物,障碍物的情况直接为0就好,在初始化的时候需要做这个操作,在dp的迭代过程中也要做,其他与Unique Paths I 是一样的
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
if(m <= )
return ;
int n = obstacleGrid[].size();
if(n <= )
return ;
if(obstacleGrid[][] == || obstacleGrid[m-][n-] == )
return ;
vector<vector<long> > dp(m,vector<long>(n));
dp[][] = ;
for(int i = ;i < m;i++){
if(dp[i-][] == || obstacleGrid[i][] == )
dp[i][] = ;
else
dp[i][] = ;
}
for(int i = ;i < n;i++){
if(dp[][i-] == || obstacleGrid[][i] == )
dp[][i] = ;
else
dp[][i] = ;
}
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
if(obstacleGrid[i][j] == )
dp[i][j] = ;
else
dp[i][j] = dp[i-][j] + dp[i][j-];
}
}
return dp[m-][n-];
}
};