Search code examples
ctime-complexitybinary-search-treedynamic-programmingcatalan

Catalan Number in using Dynamic Prog


I was calculating the number of Binary Search Trees with n nodes, and I found out that it is Catalan Number.

Now, using DP, here's my attempt.

create arr[n+1];
arr[0]=1;
arr[1]=1;
for(i=2;i<n+1;i++)
  arr[i]=0;
  for(j=1;j<i;j++)
    arr[i]+=arr[i-j]*arr[j];

//arr[n] gives the answer?

Is this the right way?

Can it be any better?


Solution

  • I don't think that your code works. Do you mean the number of unique Binary Search Trees with numbers from 1 to n?

    For n = 3, the number should be 5. But your code gave me the result 2.

    1         3     3      2      1
     \       /     /      / \      \
      3     2     1      1   3      2
     /     /       \                 \
    2     1         2                 3
    

    Here is my solution:

    int numTrees(int n) {
        int dp[n+1];
        memset(dp, 0, sizeof(dp));
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i <= n; ++i)
            for (int j = 1; j <= i; j++)
                dp[i] += dp[j-1] * dp[i-j];
        return dp[n];
    }
    

    For Catalan Number, P(3) = P(1)P(2) + P(2)P(1).

    But in this problem, P(3) = P(0)P(2) + P(1)P(1) + P(2)P(0).

    So, I guess it's not Catalan Numbers. Hope this could help you.