Skip to content

Commit

Permalink
Decode Ways
Browse files Browse the repository at this point in the history
  • Loading branch information
Sunjae95 committed Aug 23, 2024
1 parent 5ac3b56 commit 0e185f4
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions decode-ways/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* @description
* time complexity: O(n^2)
* space complexity: O(n)
*
* brainstorming:
* 1. dp -> dp[i] = dp[i-1] + count
* 2. recursive function
*
* strategy:
* https://www.algodale.com/problems/decode-ways/
*
* result:
* 1. couldn't think of the conditions
* true: 1~9, 10~27
* false: 0, 0N, 28↑
* 2. persist solution that is top down
*/

// https://www.algodale.com/problems/decode-ways/ Solve 1
var numDecodings = function (s) {
const search = (start) => {
if (start === s.length) return 1;
if (s[start] === "0") return 0;
if (start + 1 < s.length && Number(`${s[start]}${s[start + 1]}`) < 27) {
return search(start + 1) + search(start + 2);
}
return search(start + 1);
};

return search(0);
};

// https://www.algodale.com/problems/decode-ways/ Solve 2
var numDecodings = function (s) {
const memo = new Map();
memo.set(s.length, 1);

const search = (start) => {
if (!!memo.get(start)) return memo.get(start);

if (s[start] === "0") memo.set(start, 0);
else if (start + 1 < s.length && Number(`${s[start]}${s[start + 1]}`) < 27)
memo.set(start, search(start + 1) + search(start + 2));
else memo.set(start, search(start + 1));

return memo.get(start);
};

return search(0);
};

// https://www.algodale.com/problems/decode-ways/ Solve 3
var numDecodings = function (s) {
const dp = Array.from({ length: s.length + 1 }, (_, i) =>
i === s.length ? 1 : 0
);

for (let i = s.length - 1; i >= 0; i--) {
if (s[i] === "0") dp[i] = 0;
else if (i + 1 < s.length && Number(`${s[i]}${s[i + 1]}`) < 27)
dp[i] = dp[i + 1] + dp[i + 2];
else dp[i] = dp[i + 1];
}

return dp[0];
};

0 comments on commit 0e185f4

Please sign in to comment.