File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @return {number }
4+ */
5+ var numDecodings = function ( s ) {
6+ if ( s [ 0 ] === '0' ) return 0 ;
7+
8+ let count = 0 ;
9+ const memo = { } ;
10+
11+ function backtrack ( index , curr ) {
12+ // ๊ธฐ์ ์กฐ๊ฑด: ๋ฌธ์์ด ๋๊น์ง ์์ผ๋ฉด ์ ํจํ ๋์ฝ๋ฉ ๋ฐ๊ฒฌ
13+ if ( index === s . length ) {
14+ count ++ ;
15+ return ;
16+ }
17+
18+ // ๋ฉ๋ชจ์ด์ ์ด์
ํค ์์ฑ
19+ const key = index ;
20+ if ( memo [ key ] !== undefined ) {
21+ count += memo [ key ] ;
22+ return ;
23+ }
24+
25+ // ์ด์ ์นด์ดํธ ์ ์ฅ
26+ const prevCount = count ;
27+
28+ // Case 1: ํ ์๋ฆฌ ์ซ์๋ก ๋์ฝ๋ฉ (1~9)
29+ if ( s [ index ] !== '0' ) {
30+ const oneDigit = s [ index ] ;
31+ curr . push ( oneDigit ) ;
32+ backtrack ( index + 1 , curr ) ;
33+ curr . pop ( ) ;
34+ }
35+
36+ // Case 2: ๋ ์๋ฆฌ ์ซ์๋ก ๋์ฝ๋ฉ (10~26)
37+ if ( index + 1 < s . length ) {
38+ const twoDigit = s . substring ( index , index + 2 ) ;
39+ const num = parseInt ( twoDigit ) ;
40+ if ( num >= 10 && num <= 26 ) {
41+ curr . push ( twoDigit ) ;
42+ backtrack ( index + 2 , curr ) ;
43+ curr . pop ( ) ;
44+ }
45+ }
46+
47+ // ํ์ฌ ์์น์์ ๋ฐ๊ฒฌํ ๋์ฝ๋ฉ ๋ฐฉ๋ฒ ์ ์ ์ฅ
48+ memo [ key ] = count - prevCount ;
49+ }
50+
51+ backtrack ( 0 , [ ] ) ;
52+ return count ;
53+ } ;
You canโt perform that action at this time.
0 commit comments