Unique Paths II - LeetCode
题目链接
注意点
- 数字很大,结果可能会溢出
解法
解法一:dp,走到某一格的位置等于它左边和上面格子(前提是格子的值不为1)的dp值之和。其实只需要一个一维数组也可以实现。时间复杂度O(mn)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if(obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0 || obstacleGrid[0][0] == 1) return 0;
int m = obstacleGrid[0].size(),n = obstacleGrid.size();
int i,j;
long int dp[n][m];
for(i = 0; i < n;i++)
{
for(j = 0;j < m;j++)
dp[i][j] = 0;
}
dp[0][0] = 1;
for(i = 0;i < n;i++)
{
for(j = 0;j < m;j++)
{
if(i-1 >= 0 && obstacleGrid[i-1][j] != 1 && obstacleGrid[i][j] != 1) dp[i][j] += dp[i-1][j];
if(j-1 >= 0 && obstacleGrid[i][j-1] != 1 && obstacleGrid[i][j] != 1) dp[i][j] += dp[i][j-1];
}
}
return dp[n-1][m-1];
}
};
小结
- 动态规划题