I was recently practicing dynamic programming and came across the nth-Catalan problem. After looking at the problem and the formula for the Catalan numbers, I was confused about how to code the solution dynamically. I decided to look at this problem mathematically and derived the formula:
(1) C_n = (4n - 2) / (n + 1) * C_{n - 1}
By doing so I was easily able to translate it into code:
//Not sure if this solution is dynamic or not.
int ln = 1;
for(int i = 2; i <= n; i++){
ln = ln * (4*i - 2) / (i + 1);
}
return ln;
After implementing my solution and checking it, I looked at the dynamic approach to solve the problem. I was surprised to see that it followed a recursive formula that is derived from the initial formula:
(2) C_n = sum(n, i=0) (C_i * C_{n - i - 1})
This program runs at a time complexity of O(N^2) as opposed to my method with a complexity of O(N).
Looking on the internet, I found that the equation I derived is the simplified recursive formula. However, even after finding multiple coding solutions, I was unable to find any that used the simplified formula to solve the nth-Catalan problem in O(N) time.
The closest I got is a O(N) method that uses the formula:
(3) C_n = (2n choose n)/(n + 1)
Is there a reason why the simplified formula (1) is not used in any of the solutions I found?