1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
| class Solution {
public:
/*
## 解题思路
* 动态规划
1. f(m,n)代表到达m,n的方法数;
2. f(m,n) = f(m-1,n) + f(m, n-1)
3. 如果obstracleGrid[m][n]==1, 则f(m,n) = 0, 否则f(m,n) > 0;
4. f(0,n),f(m,0)作为边界情况,需要单独处理;
*/
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> f(m, vector<int>(n, 0));
for (int i=0; i <m; i++) {
for(int j=0; j<n; j++) {
if (obstacleGrid[i][j] == 1) {
f[i][j] = 0;
} else if (i == 0 || j==0) {
if (i==0 && j==0) {
f[i][j] = 1-obstacleGrid[i][j];
} else if (j>0) {
f[i][j] = f[i][j-1];
} else if(i>0) {
f[i][j] = f[i-1][j];
}
} else {
f[i][j] = f[i-1][j] + f[i][j-1];
}
}
}
return f[m-1][n-1];
}
/*
* 优化:
5. 可以考虑扩展一行和一列,将第0行第0列变为第1行,第1列, 第0行第0列初始化为0,进行统一处理;
6. 设置[0,1]为起始点,即f(0,1)=1;
*/
int uniquePathsWithObstacles2(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> f(m+1, vector<int>(n+1, 0));
f[0][1]=1; //从扩展的[0,1]格开始出发,[1,0]也可以,但不能同时
for (int i=1; i <=m; i++) {
for(int j=1; j<=n; j++) {
if (obstacleGrid[i-1][j-1] == 0) { //obstacleGrid没有扩展
f[i][j] = f[i-1][j] + f[i][j-1];
}
}
}
return f[m][n];
}
};
|