How can the following recursion + memoization code be converted into a tabulation format dynamic programming solution?
The code is working but I want to improve it.
The challenge I am facing is handling negative indices (count < 0) and shifting them to the positive side.
Problem link: https://leetcode.com/problems/valid-parenthesis-string/description/
public static boolean checkValidStringMem(String s)
{
int n = s.length();
Boolean[][] mem = new Boolean[n][n + 1];
return checkValidStringMem(s, 0, 0, mem);
}
public static boolean checkValidStringMem(String s, int i, int count, Boolean[][] mem)
{
if (count < 0)
return false;
if (i == s.length())
return count == 0;
if (mem[i][count] != null)
return mem[i][count];
if (s.charAt(i) == '(')
return mem[i][count] = checkValidStringMem(s, i + 1, count + 1, mem);
else if (s.charAt(i) == ')')
return mem[i][count] = checkValidStringMem(s, i + 1, count - 1, mem);
else // '*' can be ')' or '(' or empty character
{
return mem[i][count] = checkValidStringMem(s, i + 1, count + 1, mem) ||
checkValidStringMem(s, i + 1, count - 1, mem) ||
checkValidStringMem(s, i + 1, count, mem);
}
}