题目传送
思路:很简单,直接设置左上角为1,dp[i][j] = dp[i-1][j] + dp[i][j-1]
class Solution {
public:
int uniquePaths(int m, int n) {
long long dp[105][105] = {0};
memset(dp,0,sizeof(dp));
dp[1][1] = 1;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
if(i == 1 && j == 1) continue;
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
// cout << dp[n][m] << endl;
return dp[n][m];
}
};
加强版:
把路障的地方不走就是了
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
long long dp[105][105] = {0};
memset(dp,0,sizeof(dp));
dp[1][1] = 1;
int n = obstacleGrid.size(),m = obstacleGrid[0].size();
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
if((i == 1 && j == 1) || obstacleGrid[i-1][j-1]) continue;
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
// cout << dp[n][n] << endl;
if(obstacleGrid[0][0] == 1) return 0;
else return dp[n][m];
}
};