-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09_UniquePath.cpp
126 lines (115 loc) · 2.72 KB
/
09_UniquePath.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// https://leetcode.com/problems/unique-paths/
// There is a robot on an m x n grid. The robot is initially located at the top-left corner
// (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1]
// [n - 1]). The robot can only move either down or right at any point in time.
// Given the two integers m and n, return the number of possible unique paths that the
// robot can take to reach the bottom-right corner.
// The test cases are generated so that the answer will be less than or equal to 2 * 109.
#include <bits/stdc++.h>
using namespace std;
class Solution4
{
// Recursive solution : Tabulation : Space optimisation
public:
int uniquePaths(int m, int n)
{
vector<int> prev(n, 1);
for (int i = 1; i < m; ++i)
{
int left = 1;
for (int j = 1; j < n; ++j)
{
prev[j] += left;
left = prev[j];
}
}
return prev[n-1];
}
};
class Solution3
{
// Recursive solution : Tabulation
public:
int uniquePaths(int m, int n)
{
vector<vector<int>> dp(m, vector<int>(n, 1));
for (int i = 1; i < m; ++i)
{
for (int j = 1; j < n; ++j)
{
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};
class Solution2
{
// Recursive solution : Memoization
public:
int uniquePaths(int m, int n)
{
vector<vector<int>> dp(m, vector<int>(n, -1));
return solve(m - 1, n - 1, dp);
}
int solve(int m, int n, vector<vector<int>> &dp)
{
if (m < 0 || n < 0)
return 0;
if (m == 0 && n == 0)
{
return 1;
}
if (dp[m][n] != -1)
{
return dp[m][n];
}
return dp[m][n] = solve(m - 1, n, dp) + solve(m, n - 1, dp);
}
};
class Solution1
{
// Recursive solution : Improved
public:
int uniquePaths(int m, int n)
{
if (m < 1 || n < 1)
return 0;
if (m == 1 && n == 1)
{
return 1;
}
return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}
};
class Solution
{
// Recursive solution
public:
int uniquePaths(int m, int n)
{
int ans = 0;
solve(m - 1, n - 1, ans);
return ans;
}
void solve(int m, int n, int &ans)
{
if (m < 0 || n < 0)
return;
if (m == 0 && n == 0)
{
++ans;
return;
}
solve(m - 1, n, ans);
solve(m, n - 1, ans);
}
};
int main()
{
Solution4 Obj1;
cout << Obj1.uniquePaths(3, 7);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}