
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
Input: ‘S’ = "11106"
Output: 2
The possible ways are:-
(1 1 10 6),
(11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
The first line contains ‘T’, denoting the number of test cases.
Each test case's first and only line contains the string ‘S’.
Return the number of ways to decode the string ‘S’.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= | S | <= 100
Time Limit: 1 sec
The above approach took a lot of execution time because we call the function numDecodingsUtil for one substring more than once. So we can optimize it, and the best way to optimize it will be using dynamic programming to remember the answers for substrings we already calculated.
The new things we do here is just that we store the answers returned by numDecodingsUtil in an array ‘DP’, where DP[i] denotes the number of ways to decode string S[i, N], and every time there is the function call for numDecodingsUtil at index i, we check if we’ve already calculated the value of DP[i].
Function numDecodingsUtil( string S, int i, int N , [int] DP)
You can clearly see here that the answer for an ith index is either the sum of the answer for (i-1)th index and (i-2)th index (in the case we’re able to use option2) or just equal to the answer of (i-1)th index (in the case we’re only going for option1). So we’re going to use this fact and just store the values for (i-1)th index and (i-2)th index into two variables ‘prev’ and ‘secondPrev’ respectively.