Skip to content

Commit 20e020d

Browse files
authored
Create decodeways.cpp
1 parent 92c1069 commit 20e020d

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Dynamic-Programming/decodeways.cpp

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
91. Decode Ways
3+
4+
A message containing letters from A-Z can be encoded into numbers using the following mapping:
5+
6+
'A' -> "1"
7+
'B' -> "2"
8+
...
9+
'Z' -> "26"
10+
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
11+
12+
"AAJF" with the grouping (1 1 10 6)
13+
"KJF" with the grouping (11 10 6)
14+
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
15+
16+
Given a string s containing only digits, return the number of ways to decode it.
17+
18+
The answer is guaranteed to fit in a 32-bit integer.
19+
20+
21+
22+
Example 1:
23+
24+
Input: s = "12"
25+
Output: 2
26+
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
27+
Example 2:
28+
29+
Input: s = "226"
30+
Output: 3
31+
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
32+
Example 3:
33+
34+
Input: s = "0"
35+
Output: 0
36+
Explanation: There is no character that is mapped to a number starting with 0.
37+
The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
38+
Hence, there are no valid ways to decode this since all digits need to be mapped.
39+
Example 4:
40+
41+
Input: s = "06"
42+
Output: 0
43+
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
44+
45+
**/
46+
47+
class Solution {
48+
public:
49+
unordered_map<int, int> dp;
50+
int recursiveMemo(int pos, string s) {
51+
if(s[pos] == '0') return 0; // if the first char is 0, terminate by returning zero
52+
int n = s.size();
53+
if(pos == n || pos == n-1) return 1; // terminating case of the recursion
54+
55+
if(dp.find(pos)!= dp.end()) return dp[pos];
56+
57+
int ans = recursiveMemo(pos+1, s); // decode next character
58+
// check for 2 characters
59+
if(stoi(s.substr(pos, 2)) <=26) { // decode 2 characters
60+
ans+= recursiveMemo(pos+2, s);
61+
}
62+
dp[pos] = ans;
63+
return ans;
64+
65+
}
66+
67+
int numDecodings(string s) {
68+
return recursiveMemo(0,s);
69+
}
70+
};

0 commit comments

Comments
 (0)