Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit efaa04f

Browse files
更新 0063.不同路径II.md Java代码
原Java代码修改为更加清晰简明的代码 添加空间优化版本的代码
1 parent a5723e1 commit efaa04f

File tree

1 file changed

+44
-14
lines changed

1 file changed

+44
-14
lines changed

‎problems/0063.不同路径II.md

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -210,24 +210,54 @@ public:
210210
```java
211211
class Solution {
212212
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
213-
int n = obstacleGrid.length, m = obstacleGrid[0].length;
214-
int[][] dp = new int[n][m];
215-
216-
for (int i = 0; i < m; i++) {
217-
if (obstacleGrid[0][i] == 1) break; //一旦遇到障碍,后续都到不了
218-
dp[0][i] = 1;
213+
int m = obstacleGrid.length;
214+
int n = obstacleGrid[0].length;
215+
int[][] dp = new int[m][n];
216+
217+
//如果在起点或终点出现了障碍,直接返回0
218+
if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) {
219+
return 0;
219220
}
220-
for (int i =0; i < n; i++) {
221-
if (obstacleGrid[i][0] == 1) break; ////一旦遇到障碍,后续都到不了
222-
dp[i][0] = 1;
221+
222+
for (int i =0; i < m &&obstacleGrid[i][0] == 0; i++) {
223+
dp[i][0] = 1;
223224
}
224-
for (int i = 1; i < n; i++) {
225-
for (int j = 1; j < m; j++) {
226-
if (obstacleGrid[i][j] == 1) continue;
227-
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
225+
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
226+
dp[0][j] = 1;
227+
}
228+
229+
for (int i = 1; i < m; i++) {
230+
for (int j = 1; j < n; j++) {
231+
dp[i][j] = (obstacleGrid[i][j] == 0) ? dp[i - 1][j] + dp[i][j - 1] : 0;
232+
}
233+
}
234+
return dp[m - 1][n - 1];
235+
}
236+
}
237+
```
238+
239+
```java
240+
// 空间优化版本
241+
class Solution {
242+
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
243+
int m = obstacleGrid.length;
244+
int n = obstacleGrid[0].length;
245+
int[] dp = new int[n];
246+
247+
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
248+
dp[j] = 1;
249+
}
250+
251+
for (int i = 1; i < m; i++) {
252+
for (int j = 0; j < n; j++) {
253+
if (obstacleGrid[i][j] == 1) {
254+
dp[j] = 0;
255+
} else if (j != 0) {
256+
dp[j] += dp[j - 1];
257+
}
228258
}
229259
}
230-
return dp[n - 1][m -1];
260+
return dp[n - 1];
231261
}
232262
}
233263
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /