Skip to content

Commit e587e27

Browse files
committed
decode ways solution
1 parent 17c86e8 commit e587e27

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

decode-ways/dylan-jung.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
int mem[100];
4+
string str;
5+
6+
bool isValid(string s) {
7+
if(s.size() == 1) {
8+
return '1' <= s[0] && s[0] <= '9';
9+
}
10+
else if(s.size() == 2) {
11+
if(s[0] == '1') return '0' <= s[1] && s[1] <= '9';
12+
else if(s[0] == '2') return '0' <= s[1] && s[1] <= '6';
13+
}
14+
return false;
15+
}
16+
17+
int dfs(int idx) {
18+
if(idx >= str.size()) return 1;
19+
20+
int& ret = mem[idx];
21+
if(ret != -1) return ret;
22+
ret = 0;
23+
24+
if (isValid(str.substr(idx, 1))){
25+
ret += dfs(idx+1);
26+
}
27+
if (idx < str.size() - 1 && isValid(str.substr(idx, 2))){
28+
ret += dfs(idx+2);
29+
}
30+
return ret;
31+
}
32+
33+
int numDecodings(string s) {
34+
str = s;
35+
fill(mem, mem+100, -1);
36+
return dfs(0);
37+
}
38+
};

0 commit comments

Comments
 (0)