-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path63. Unique Paths II.cpp
104 lines (83 loc) · 2.98 KB
/
63. Unique Paths II.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// -----Approach 1: Tabulation (1st way -> more efficient) ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/unique-paths-ii/
Time: 0 ms (Beats 100%), Space: 7.6 MB (Beats 83.74%)
*/
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m= obstacleGrid.size();
int n= obstacleGrid[0].size();
int dp[m][n];
if(obstacleGrid[0][0]==1 || obstacleGrid[m-1][n-1]==1) return 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(i == 0 && j == 0) dp[i][j]=1;
else{
int up=0, left=0;
if(i>0 && !obstacleGrid[i-1][j]) up= dp[i-1][j];
if(j>0 && !obstacleGrid[i][j-1]) left= dp[i][j-1];
dp[i][j]= up + left;
}
}
}
return dp[m-1][n-1];
}
};
// -----Approach 1: Tabulation (2nd way) ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/unique-paths-ii/
Time: 7 ms (Beats 34.84%), Space: 7.6 MB (Beats 93.92%)
*/
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m= obstacleGrid.size();
int n= obstacleGrid[0].size();
int dp[m][n];
if(obstacleGrid[0][0]==1 || obstacleGrid[m-1][n-1]==1) return 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(i == 0 && j == 0) dp[i][j]=1;
else if(obstacleGrid[i][j]==1) dp[i][j]=0;
else{
int up=0, left=0;
if(i>0) up= dp[i-1][j];
if(j>0) left= dp[i][j-1];
dp[i][j]= up + left;
}
}
}
return dp[m-1][n-1];
}
};
// -----Approach 2: Space Optimisation ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/unique-paths-ii/
Time: 3 ms (Beats 79.88%), Space: 7.8 MB (Beats 51.10%)
*/
// both ways in space optimisation similar to tabulation have nearly same running time and memory
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m= obstacleGrid.size();
int n= obstacleGrid[0].size();
vector<int> prev(n, 0);
if(obstacleGrid[0][0]==1 || obstacleGrid[m-1][n-1]==1) return 0;
for(int i=0; i<m; i++){
vector<int> curr(n, 0);
for(int j=0; j<n; j++){
if(i == 0 && j == 0) curr[j]=1;
else if(obstacleGrid[i][j]==1) curr[j]=0;
else{
int up=0, left=0;
if(i>0) up= prev[j];
if(j>0) left= curr[j-1];
curr[j]= up + left;
}
}
prev= curr;
}
return prev[n-1];
}
};