1. Recursive Branching
Intuition
At each index i, branch into decoding a 1-digit number and/or a 2-digit number.
Algorithm
- Define
dfs(i). - If
i == s.length, return 1. - If
s[i] == '0', return 0. - Option 1: decode 1 digit ->
ways = dfs(i + 1). - Option 2: if
i + 1 < s.lengthand substrings[i..i+1]is between10and26,ways += dfs(i + 2). - Return
ways.
#include <iostream>#include <string> using namespace std; int dfs(int i, const string& s) { if (i == (int)s.length()) return 1; if (s[i] == '0') return 0; int ways = dfs(i + 1, s); if (i + 1 < (int)s.length()) { int twoDigit = (s[i] - '0') * 10 + (s[i + 1] - '0'); if (twoDigit >= 10 && twoDigit <= 26) { ways += dfs(i + 2, s); } } return ways;} int numDecodingsRec(string s) { return dfs(0, s);} int main() { string s = "226"; cout << "Decode Ways (Recursive): " << numDecodingsRec(s) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack