-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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) |