I was able to solve the problem given in the title using a recursive DP, but got TLE. This was due to the fact that the input string can have about 5000 digits which leads to a lot of sub function calls, and my program is not able to compute the result, even on my on computer.
The question is as follows: ACODE
My solution is the following:
import sys
def chk(word):
if word[0] == '0':
return 0
if int(word) < 27 and int(word) > 0:
return 1
else:
return 0
def dp(line):
if len(line) > 2:
return chk(line[0])*dp(line[1:]) + chk(line[:2])*dp(line[2:])
elif len(line) > 1:
return chk(line[0])*dp(line[1]) + chk(line)
else:
return chk(line)
line = sys.stdin.readline().strip()
while line != '0':
print dp(line)
line = sys.stdin.readline().strip()
Searching the internet leads to the following solution:
1) Initialize an Array of Size N with 0 and element 0 as 1
2) Loop through all the elements
3) If it is a valid single digit number, Copy the previous element's value to the current element (DP[i] = DP[i-1])
4) If it is a valid two digit number, Add the previous to previous element's value to the current element (DP[i] += DP[i-2])In one line : DP[i] = DP[i-1] {if valid single digit number} + DP[i-2] {if current and previous elements make a valid two digit number}
I'm not sure if I'm doing the same thing, because I'm not able to understand the above approach, or if there is someway to turn my recursive approach to iterative.