Given a number n, the task is to find the nth Catalan number.
The first few Catalan numbers for N = 0, 1, 2, 3, 4, 5 ... are 1, 1, 2, 5, 14, 42 ...
Solutions
Method 1: Recursion
Catalan numbers satisfy the following recursive formula.
c(0)= 1 c(1)= 1 c(2)= c(0)*c(1) + c(1)*c(0) = 2 c(3)= c(0)*c(2) + c(1)*c(1) + c(2)*c(0) = 5 c(4)= c(0)*c(3) + c(1)*c(2) + c(2)*c(1) + c(3)*c(0) = 14 c(n)= c(0)*c(n-1) + c(1)*c(n-2) .. ... .. c(n-2)*c(1) + c(n-1)*c(0)
Complexity
The time complexity of this solution is exponential O(2^n).
In addition, O(2^n) auxiliary space was used by the recursion stack.
Method 2: Memoization
The Memoization Technique is basically an extension to the recursive approach so that we can overcome the problem of calculating redundant cases and thus decrease time complexity.
We can see that in each recursive call only the value of "n" changes, so we can store and reuse the result of a function(..n) call using a "n+1" array.
The array will store a particular state (n) if we get it the first time.
Now, if we come across the same state (n) again, instead of calculating it in exponential complexity, we can directly return its result stored in the table in constant time.
Complexity
The time complexity of this solution is (n).
In addition, O(n) auxiliary space was used by the table.