Recursion (Brute Force)
Intuition
At each position we can decode one digit or two digits (if the two-digit number is between 10 and 26). We recursively count the total ways from the current position to the end. A digit '0' cannot start a valid code, so we return 0 for that branch. Without memoization, this has exponential time due to overlapping subproblems.
Algorithm
- If the current index equals the string length, return `1` (one valid decoding found).
- If the current character is `'0'`, return `0` (invalid).
- Count ways by decoding one digit and recursing from `index + 1`.
- If two digits form a number between 10 and 26, also add ways from `index + 2`.
- Return the total count.
O(2^n)SpaceO(n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int numDecodings(string s) {
return helper(s, 0);
}
int helper(string& s, int i) {
if (i == s.size()) return 1;
if (s[i] == '0') return 0;
int ways = helper(s, i + 1);
if (i + 1 < s.size()) {
int twoDigit = (s[i] - '0') * 10 + (s[i + 1] - '0');
if (twoDigit >= 10 && twoDigit <= 26) {
ways += helper(s, i + 2);
}
}
return ways;
}
};class Solution {
public int numDecodings(String s) {
return helper(s, 0);
}
private int helper(String s, int i) {
if (i == s.length()) return 1;
if (s.charAt(i) == '0') return 0;
int ways = helper(s, i + 1);
if (i + 1 < s.length()) {
int twoDigit = Integer.parseInt(s.substring(i, i + 2));
if (twoDigit >= 10 && twoDigit <= 26) {
ways += helper(s, i + 2);
}
}
return ways;
}
}class Solution:
def numDecodings(self, s: str) -> int:
def helper(i: int) -> int:
if i == len(s):
return 1
if s[i] == '0':
return 0
ways = helper(i + 1)
if i + 1 < len(s) and 10 <= int(s[i:i + 2]) <= 26:
ways += helper(i + 2)
return ways
return helper(0)func numDecodings(s string) int {
var helper func(i int) int
helper = func(i int) int {
if i == len(s) {
return 1
}
if s[i] == '0' {
return 0
}
ways := helper(i + 1)
if i+1 < len(s) {
twoDigit := int(s[i]-'0')*10 + int(s[i+1]-'0')
if twoDigit >= 10 && twoDigit <= 26 {
ways += helper(i + 2)
}
}
return ways
}
return helper(0)
}