I have some understanding of Catalan numbers (http://en.wikipedia.org/wiki/Catalan_number) and their applications (for ex, generating balanced parenthesized strings, balanced strings from given n+1 factors etc. I am using below two methods to generate balanced parenthesized strings. One basically uses Catalan recursive formula and another is nothing but a simple recursive function which ensures the number of left parenthesis always greater than or equal to right parenthesis. I understand why both generate correct strings and why the total number of such strings are nothing but Catalan Number.
Question:
However I am unable to understand relationship between these two approaches (algorithms)? Does the second approach also satisfy Catalan recursive relationship as the first one, but implicitly? if yes, can anyone please explain in words as I am having hard time coming up with that explanation...
Basically I am looking for some explanation in words rather than mathematically - as with first approach I can clearly see it satisfies Catalan Relationship, but not with the second one. And also please note that I am not looking for difference in efficiencies like the first one recalculating sub problems, extra space etc. - focus is only on relating the second recursion with Cartisan recursive relationship.
Related but not same as the question is not about solving them, rather difference and explanation of difference, and relating both to Cartisan recursive relationship: Valid Permutation of Parenthesis The possible number of binary search trees that can be created with N keys is given by the Nth catalan number. Why?
Appraoch 1 (using Catalan Relationship)
string[] CatalanNumber_AllPossibleParanthesis(int N)
{
Assert.IsTrue(N >= 0);
if(N==0)
{
return new string[] {" "};
}
if(N == 1)
{
return new string[] { "[]" };
}
List<string> results = new List<string>();
for (int i = 0; i <= (N - 1); i++)
{
var r1 = this.CatalanNumber_AllPossibleParanthesis(i);
var r2 = this.CatalanNumber_AllPossibleParanthesis(N - 1 - i);
foreach (var s1 in r1)
{
foreach (var s2 in r2)
{
//[c']c" - will be of the form
string r = "[" + s1.Trim() + "]" + s2.Trim();
results.Add(r);
}
}
}
return results.ToArray();
}
Approach 2 (with smple recursion by making sure #left ( >= #right
string[] GetAllPossibleParanthesis_2(int left, int right, string s)
{
if((left == 0) && (right==0))
{
return new string[] { s };
}
Assert.IsTrue(left <= right);
List<string> results = new List<string>();
if (left > 0)
{
var r = this.GetAllPossibleParanthesis_2(left - 1,
right, s + "[");
results.AddRange(r);
}
if(left <= (right-1))
{
var r = this.GetAllPossibleParanthesis_2(left,
right-1, s + "]");
results.AddRange(r);
}
return results.ToArray();
}