SRM 686, D1, 250-Pointer (BracketSequenceDiv1)

James S. Plank

Mon Oct 10 23:52:16 EDT 2016
This is a pretty classic topcoder dynamic programming problem. As always, the challenge is spotting the recursion. Let's use an example that's not in the writeup:
s = "[(])][]"    
Let's enumerate the solutions -- there are 11.

In this problem, as with many dynamic programming problems, it's best to work from left to right, concentrating on the first character of the string. So, in the case of our example, we are going to concentrate on the first character -- the left square brace:

[(])][]
The number of ways to erase characters and get valid bracketed strings is going to be the number of ways that you can do it by erasing the first character, plus the number of ways that you can do it by not erasing the first character. If we erase the first character, than we can simply call count() on the remaining characters, and that will be our answer. In the example above, we'd call:
count("(])][]");
That's nice. Now, when we don't erase the first character, we need to do something so that we can recurse on smaller strings. Let's match the first with its nearest closing square bracket. We get the following (and I'm coloring the strings for clarity):
[(])][]
The number of ways to erase characters and get correct bracket sequences, when you are not erasing the red characters, will be the number of ways for:
[(]
when you don't delete the red characters, multiplied by
)][]
when you are allowed to delete any and all characters. This turns out to be:
count("(")+1
multiplied by:
count(")][]")+1
Why the +1's? Because we want to count empty strings in these instances, and count() does not include the empty string. So you add one. It is important to realize that because you are not deleting the red characters, it's ok for the other strings to become empty, and that's why you add one to the recursive count() calls.

Next, you match the first character with the next closing square brace:

[(])][]
And you do the same thing -- it equals
(count("(])")+1)*(count("[]")+1)
Finally, you match the first character with the last closing square brace:
[(])[]
And you do the same thing -- it equals
(count("(])][")+1)*(count("")+1)
Add them up, and you're done. Let's work through the numbers in our example: As you can see, the sum is 11.

Obviously, you'll have to memoize the recursion to make sure you don't have exponential blowup.


My Solution.

/* Topcoder SRM 686, D1, 250-pointer: BracketSequenceDiv1
 * James S. Plank
 * Tue Oct 11 00:57:32 EDT 2016
 */

#include <string>
#include <vector>
#include <list>
#include <cmath>
#include <algorithm>
#include <map>
#include <set>
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

class BracketSequenceDiv1
{
    public:
        map <string, long long> Cache;
        long long count(string s);
};

long long BracketSequenceDiv1::count(string s)
{
    int i;
    long long one;
    long long b, e;
    map <string, long long>::iterator mit;

    /* Base case -- empty string equals 0 */

    if (s.size() == 0) return 0;

    /* Memoization looks at the cache first. */

    if (Cache.find(s) != Cache.end()) return Cache[s];

    /* Set one to be the answer when you erase the first character.  If the first
       character is a closing brace, that's all you can do, so return the answer
       in that case.  */

    one = count(s.substr(1));
    if (s[0] == ')' || s[0] == ']') {
        Cache[s] = one;
        return one;
    }

    /* Otherwise, for each closing brace/parenthesis that matches the first character,
       split the string in two at that point, and recurse on the first half and the
       second half, adding one to account for empty strings. Add in the products. */

    for (i = 1; i < s.size(); i++) {
        if ((s[0] == '(' && s[i] == ')') ||
            (s[0] == '[' && s[i] == ']')) {
            b = count(s.substr(1, i-1))+1;
            e = count(s.substr(i+1))+1;
            one += (b*e);
        }
    }

    /* At the end, put the value into the cache, and return. */

    Cache[s] = one;
    return one;
}