Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

For example,
Given n = 3, there are a total of 5 unique BST’s.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
C++:
01 class Solution {
02 public:
03     int numTrees(int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         vector<int> A(n+1);
07         A[0]=A[1]=1;
08         for(int i=2;i<=n;i++)
09         {
10             for(int j=0;j<i;j++)
11             {
12                 A[i]+=A[j]*A[i1j];
13             }
14         }
15         return A[n];
16     }
17 };
Advertisements
This entry was posted in Dynamic programming, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s