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
class Solution { public: int numTrees(int n) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> > vec; vector<int> one; for(int i=0;i<=n;i++){ one.resize(n-i+1,0); vec.push_back(one); } for(int j=0;j<n;j++){ vec[j][0]=1; vec[j][1]=1; }
vec[n][0]=1; for(int j=2;j<=n;j++){ for(int i=0;i<=n-j;i++){ for(int k=0;k<j;k++){ vec[i][j]+=vec[i][k]*vec[i+k+1][j-k-1]; } } } return vec[0][n]; } };