forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhewchews.ts
33 lines (28 loc) Β· 862 Bytes
/
whewchews.ts
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
function numDecodings(s: string): number {
// SC: O(N)
const memo: { [key: number]: number } = { [s.length]: 1 };
// TC: O(N)
const dfs = (start: number): number => {
if (start in memo) {
return memo[start];
}
if (s[start] === "0") {
// 0μΌλ‘ μμνλ κ²½μ° κ°λ₯ν κ²½μ°μ μκ° μμ
memo[start] = 0;
} else if (
start + 1 < s.length &&
parseInt(s.substring(start, start + 2)) < 27
) {
// λ€μμ μ€λ κΈμκ° λκΈμ μ΄μ μκ³ , start start+1 λκΈμκ° 1~26 μ¬μ΄μ κ°μΈ κ²½μ°
memo[start] = dfs(start + 1) + dfs(start + 2);
} else {
// 1κΈμλ§ λ¨μ κ²½μ° or 첫 λκΈμκ° 27λ³΄λ€ ν° κ²½μ°
memo[start] = dfs(start + 1);
}
return memo[start];
};
// SC: μ¬κ·νΈμΆ O(N)
return dfs(0);
}
// TC: O(N)
// SC: O(N)