File tree 2 files changed +36
-0
lines changed
2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 60
60
| 59 | [ Spiral Matrix II] ( https://leetcode.com/problems/spiral-matrix-ii ) | [ ![ Java] ( assets/java.png )] ( src/SpiralMatrixII.java ) | |
61
61
| 61 | [ Rotate List] ( https://leetcode.com/problems/rotate-list ) | [ ![ Java] ( assets/java.png )] ( src/RotateList.java ) | |
62
62
| 62 | [ Unique Paths] ( https://leetcode.com/problems/unique-paths ) | [ ![ Java] ( assets/java.png )] ( src/UniquePaths.java ) | |
63
+ | 63 | [ Unique Paths II] ( https://leetcode.com/problems/unique-paths-ii ) | [ ![ Java] ( assets/java.png )] ( src/UniquePathII.java ) | |
63
64
| 66 | [ Plus One] ( https://leetcode.com/problems/plus-one ) | [ ![ Java] ( assets/java.png )] ( src/PlusOne.java ) [ ![ Python] ( assets/python.png )] ( python/plus_one.py ) | |
64
65
| 67 | [ Add Binary] ( https://leetcode.com/problems/add-binary ) | [ ![ Java] ( assets/java.png )] ( src/AddBinary.java ) [ ![ Python] ( assets/python.png )] ( python/add_binary.py ) | |
65
66
| 69 | [ Sqrt(x)] ( https://leetcode.com/problems/sqrtx ) | [ ![ Java] ( assets/java.png )] ( src/Sqrtx.java ) [ ![ Python] ( assets/python.png )] ( python/sqrt.py ) | |
Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/unique-paths-ii
2
+ // T: O(m * n)
3
+ // S: O(n)
4
+
5
+ public class UniquePathII {
6
+ public int uniquePathsWithObstacles (int [][] obstacleGrid ) {
7
+ final int rows = obstacleGrid .length , columns = obstacleGrid [0 ].length ;
8
+ if (obstacleGrid [rows - 1 ][columns - 1 ] == 1 ) return 0 ;
9
+ final int [][] memory = getMemoryTable (obstacleGrid );
10
+
11
+ int i = 0 ;
12
+ for (int row = rows - 2 ; row >= 0 ; row --, i ^= 1 ) {
13
+ memory [i ][columns - 1 ] = memory [i ^ 1 ][columns - 1 ] & (obstacleGrid [row ][columns - 1 ] ^ 1 );
14
+ for (int column = columns - 2 ; column >= 0 ; column --) {
15
+ if (obstacleGrid [row ][column ] == 1 ) {
16
+ memory [i ][column ] = 0 ;
17
+ } else {
18
+ memory [i ][column ] = memory [i ^ 1 ][column ] + memory [i ][column + 1 ];
19
+ }
20
+ }
21
+ }
22
+
23
+ return memory [i ^ 1 ][0 ];
24
+ }
25
+
26
+ private int [][] getMemoryTable (int [][] obstacles ) {
27
+ final int rows = obstacles .length , columns = obstacles [0 ].length ;
28
+ final int [][] memory = new int [2 ][columns ];
29
+ memory [1 ][columns - 1 ] = 1 ;
30
+ for (int column = columns - 2 ; column >= 0 ; column --) {
31
+ memory [1 ][column ] = memory [1 ][column + 1 ] & (obstacles [rows - 1 ][column ] ^ 1 );
32
+ }
33
+ return memory ;
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments