Skip to content

Commit 021c2bc

Browse files
committed
Decode Ways
1 parent 5ac3b56 commit 021c2bc

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

decode-ways/sunjae95.js

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

0 commit comments

Comments
 (0)