#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<string> result;
void GenerateParentheses(string& p, int left, int right, int level)
{
if (left == 0 && right == 0)
{
result.push_back(p);
return;
}
if (left > 0)
{
p[level] = '(';
GenerateParentheses(p, left-1, right+1, level+1);
}
if (right > 0)
{
p[level] = ')';
GenerateParentheses(p, left, right-1, level+1);
}
}
void GenerateParentheses(int n)
{
string parenthesis(n*2,'\0');
result.clear();
GenerateParentheses(parenthesis, n, 0, 0);
}
#define MAXNUM 100
vector<string> dp[MAXNUM][MAXNUM];
void GenerateParentheses(int left, int right)
{
if (left == 0 && right == 0)
{
dp[0][0].push_back("");
return;
}
if (left > 0)
{
vector<string>& strs = dp[left-1][right+1];
if (strs.size() <= 0)
GenerateParentheses(left-1, right+1);
for (int i = 0; i < strs.size(); ++i)
dp[left][right].push_back('(' + strs[i]);
}
if (right > 0)
{
vector<string>& strs = dp[left][right-1];
if (strs.size() <= 0)
GenerateParentheses(left, right-1);
for (int i = 0; i < strs.size(); ++i)
dp[left][right].push_back(')' + strs[i]);
}
}
vector<string>& GenerateParentheses_dp(int n)
{
if (dp[n][0].size() <=0 )
GenerateParentheses(n, 0);
return dp[n][0];
}
int main(int argc, char** argv)
{
for (int i = 13; i > 0; --i)
{
int n = i;
GenerateParentheses(n);
GenerateParentheses_dp(n);
cout << n <<": ";
if (result == dp[n][0])
cout << "The same result for Backtracing and Dynamic Programming\n";
else
cout << "Different!!!!!!!!";
}
return 0;
}