-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunique-paths.ts
More file actions
30 lines (28 loc) · 797 Bytes
/
Copy pathunique-paths.ts
File metadata and controls
30 lines (28 loc) · 797 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
/**
* 62. Unique Paths (Medium)
* Link: https://leetcode.com/problems/unique-paths/
*
* A robot starts at the top-left of an m x n grid and can only move right or
* down. Return the number of distinct paths to the bottom-right corner.
*
* Example:
* Input: m = 3, n = 7
* Output: 28
*
* Approach:
* DP: paths to a cell = paths from above + paths from the left. The first row
* and column are all 1 (single straight path). We compress the table to one
* row, updating in place: row[j] += row[j-1].
*
* Time: O(m * n)
* Space: O(n)
*/
export function uniquePaths(m: number, n: number): number {
const row = new Array<number>(n).fill(1);
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
row[j] += row[j - 1];
}
}
return row[n - 1];
}