[InterviewBit] Ways to Decode

Ways to Decode

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
long long dp[101010], mod = 1e9 + 7;
long long helper(string& A, int p) {
if(A.size() == p) return 1;
if(dp[p] != -1) return dp[p];
if(A[p] == '0') return 0;
if(A[p] >= '3') return dp[p] = helper(A, p + 1);
if(p + 1 == A.size()) return dp[p] = helper(A, p + 1);
if(A[p] == '1') return dp[p] = (helper(A,p+1) + helper(A,p+2)) % mod;
if(A[p + 1] >= '7') return dp[p] = helper(A, p + 1);
return dp[p] = (helper(A,p+1) + helper(A,p+2)) % mod;
}
int Solution::numDecodings(string A) {
memset(dp,-1,sizeof dp);
return helper(A,0);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/10/PS/interviewbit/ways-to-decode/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.