forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0062-unique-paths.cpp
31 lines (26 loc) · 824 Bytes
/
0062-unique-paths.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
/*
Given grid, return # of unique paths from top-left to bottom-right
Ex. m = 3, n = 2 -> 3 unique paths (R->D->D, D->D->R, D->R->D)
DP: edges have 1 unique path, inner cells consider where it comes from
Recurrence relation: grid[i][j] = grid[i-1][j] + grid[i][j-1]
Time: O(m x n)
Space: O(m x n)
*/
classSolution {
public:
intuniquePaths(int m, int n) {
vector<vector<int>> grid(m, vector<int>(n, 0));
for (int i = 0; i < m; i++) {
grid[i][0] = 1;
}
for (int j = 0; j < n; j++) {
grid[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
}
}
return grid[m - 1][n - 1];
}
};