-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0062-unique-paths.cpp
More file actions
36 lines (34 loc) · 924 Bytes
/
0062-unique-paths.cpp
File metadata and controls
36 lines (34 loc) · 924 Bytes
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
#include<vector>
using namespace std;
/*
* Solution 1
* class Solution {
private:
int recur(int m, int n, int i, int j, vector<vector<int>>&dp) {
if (i==m-1&&j==n-1) return 1;
dp[i][j] = 0;
if (i<m-1) dp[i][j] += dp[i+1][j] < 0 ? recur(m, n, i+1, j, dp) : dp[i+1][j];
if (j<n-1) dp[i][j] += dp[i][j+1] < 0 ? recur(m, n, i, j+1, dp) : dp[i][j+1];
return dp[i][j];
}
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp (m, vector<int>(n, -1));
return recur(m, n, 0, 0, dp);
}
};*/
// Solution 2: Space optimisation
class Solution {
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
vector<int> dp (n, 1);
dp[n-1] = 0;
for (int i = m-2;i>=0;i--) {
dp[n-1] = 1;
for (int j = n-2;j>=0;j--)
dp[j] += dp[j+1];
}
return dp[0];
}
};