|
| 1 | +//! 다시 풀어야 하는 문제 |
| 2 | + |
| 3 | +// Time limit 초과 |
| 4 | +const numDecodings_timeLimit = function (s) { |
| 5 | + let answer = 0; |
| 6 | + |
| 7 | + function recursion(idx, remains) { |
| 8 | + if (idx === remains.length) { |
| 9 | + answer++; |
| 10 | + return; |
| 11 | + } |
| 12 | + |
| 13 | + const one = remains.slice(idx, idx + 1); |
| 14 | + if (+one >= 1 && +one <= 9) { |
| 15 | + recursion(idx + 1, remains); |
| 16 | + } |
| 17 | + |
| 18 | + if (idx + 1 < remains.length) { |
| 19 | + const two = remains.slice(idx, idx + 2); |
| 20 | + if (+two >= 10 && +two <= 26) { |
| 21 | + recursion(idx + 2, remains); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + recursion(0, s); |
| 27 | + |
| 28 | + return answer; |
| 29 | +}; |
| 30 | + |
| 31 | +// 메모이제이션 적용 |
| 32 | +const numDecodings = function (s) { |
| 33 | + function recursion(idx, remains, memo = {}) { |
| 34 | + if (idx === remains.length) return 1; |
| 35 | + |
| 36 | + if (idx in memo) return memo[idx]; |
| 37 | + |
| 38 | + let answer = 0; |
| 39 | + |
| 40 | + const one = remains.slice(idx, idx + 1); |
| 41 | + if (+one >= 1 && +one <= 9) { |
| 42 | + answer += recursion(idx + 1, remains, memo); |
| 43 | + } |
| 44 | + |
| 45 | + if (idx + 1 < remains.length) { |
| 46 | + const two = remains.slice(idx, idx + 2); |
| 47 | + if (+two >= 10 && +two <= 26) { |
| 48 | + answer += recursion(idx + 2, remains, memo); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + memo[idx] = answer; |
| 53 | + return answer; |
| 54 | + } |
| 55 | + |
| 56 | + return recursion(0, s, {}); |
| 57 | +}; |
0 commit comments