Skip to content

Commit 1fe8c7d

Browse files
committed
Feat: 62. Unique Paths
1 parent efa8902 commit 1fe8c7d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

unique-paths/HC-kang.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* Solution 1. recursive - failed with Stack Overflow
3+
*/
4+
function uniquePaths(m: number, n: number): number {
5+
function factorialMemo() {
6+
const cache = [0, 1];
7+
return function factorial(n: number) {
8+
if (cache[n]) return cache[n];
9+
cache[n] = n * factorial(n - 1);
10+
return cache[n];
11+
};
12+
}
13+
14+
const factorial = factorialMemo();
15+
const total = m + n - 2;
16+
const right = m - 1;
17+
return Math.round(
18+
factorial(total) / (factorial(right) * factorial(total - right))
19+
);
20+
}
21+
22+
/**
23+
* Solution 2. for loop (with some 야매.. but it works)
24+
* https://leetcode.com/problems/unique-paths
25+
* T.C. O(m + n)
26+
* S.C. O(m + n)
27+
*/
28+
function uniquePaths(m: number, n: number): number {
29+
function factorialMemo() {
30+
const cache = [1, 1];
31+
return function factorial(n: number) {
32+
if (cache[n]) return cache[n];
33+
let result = cache[cache.length - 1];
34+
for (let i = cache.length; i <= n; i++) {
35+
result = result * i;
36+
cache[i] = result;
37+
}
38+
return result;
39+
};
40+
}
41+
42+
const factorial = factorialMemo();
43+
const total = m + n - 2;
44+
const right = m - 1;
45+
return Math.round(
46+
factorial(total) / (factorial(right) * factorial(total - right))
47+
);
48+
}
49+
50+
/**
51+
* Solution 3. DP
52+
* T.C. O(m * n)
53+
* S.C. O(m * n)
54+
*/
55+
function uniquePaths(m: number, n: number): number {
56+
const dp: number[][] = Array.from({ length: m }, () => Array(n).fill(1));
57+
58+
for (let i = 1; i < m; i++) {
59+
for (let j = 1; j < n; j++) {
60+
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
61+
}
62+
}
63+
64+
return dp[m - 1][n - 1];
65+
}

0 commit comments

Comments
 (0)