0

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);
    }
}
2
  • 2
    Does your program work, and you want to improve it? Or are you getting some sort of error? If the former, consider whether or not it is better asked here or at Code Review . If the latter, please edit the question to clarify how the program fails. Before moving to Code Review, please review their good question standards. Commented Feb 12 at 17:59
  • Question on Code Review: codereview.stackexchange.com/questions/295349/… Commented Feb 22 at 17:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.