|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * time complexity: O(n^2) |
| 4 | + * space complexity: O(n) |
| 5 | + * |
| 6 | + * brainstorming: |
| 7 | + * 1. dp -> dp[i] = dp[i-1] + count |
| 8 | + * 2. recursive function |
| 9 | + * |
| 10 | + * strategy: |
| 11 | + * https://www.algodale.com/problems/decode-ways/ |
| 12 | + * |
| 13 | + * result: |
| 14 | + * 1. couldn't think of the conditions |
| 15 | + * true: 1~9, 10~27 |
| 16 | + * false: 0, 0N, 28↑ |
| 17 | + * 2. persist solution that is top down |
| 18 | + */ |
| 19 | + |
| 20 | +// https://www.algodale.com/problems/decode-ways/ Solve 1 |
| 21 | +var numDecodings = function (s) { |
| 22 | + const search = (start) => { |
| 23 | + if (start === s.length) return 1; |
| 24 | + if (s[start] === "0") return 0; |
| 25 | + if (start + 1 < s.length && Number(`${s[start]}${s[start + 1]}`) < 27) { |
| 26 | + return search(start + 1) + search(start + 2); |
| 27 | + } |
| 28 | + return search(start + 1); |
| 29 | + }; |
| 30 | + |
| 31 | + return search(0); |
| 32 | +}; |
| 33 | + |
| 34 | +// https://www.algodale.com/problems/decode-ways/ Solve 2 |
| 35 | +var numDecodings = function (s) { |
| 36 | + const memo = new Map(); |
| 37 | + memo.set(s.length, 1); |
| 38 | + |
| 39 | + const search = (start) => { |
| 40 | + if (!!memo.get(start)) return memo.get(start); |
| 41 | + |
| 42 | + if (s[start] === "0") memo.set(start, 0); |
| 43 | + else if (start + 1 < s.length && Number(`${s[start]}${s[start + 1]}`) < 27) |
| 44 | + memo.set(start, search(start + 1) + search(start + 2)); |
| 45 | + else memo.set(start, search(start + 1)); |
| 46 | + |
| 47 | + return memo.get(start); |
| 48 | + }; |
| 49 | + |
| 50 | + return search(0); |
| 51 | +}; |
| 52 | + |
| 53 | +// https://www.algodale.com/problems/decode-ways/ Solve 3 |
| 54 | +var numDecodings = function (s) { |
| 55 | + const dp = Array.from({ length: s.length + 1 }, (_, i) => |
| 56 | + i === s.length ? 1 : 0 |
| 57 | + ); |
| 58 | + |
| 59 | + for (let i = s.length - 1; i >= 0; i--) { |
| 60 | + if (s[i] === "0") dp[i] = 0; |
| 61 | + else if (i + 1 < s.length && Number(`${s[i]}${s[i + 1]}`) < 27) |
| 62 | + dp[i] = dp[i + 1] + dp[i + 2]; |
| 63 | + else dp[i] = dp[i + 1]; |
| 64 | + } |
| 65 | + |
| 66 | + return dp[0]; |
| 67 | +}; |
0 commit comments