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
很简单。
1 class Solution {
2 public:
3 int numTrees(int n) {
4 // Start typing your C/C++ solution below
5 // DO NOT write int main() function
6 int * a;
7 a = new int[n+1];
8 a[0] = 1;
9 for(int i = 1;i <= n;i++)
10 {
11 a[i] = 0;
12 for(int j = 0;j<=i-1;j++)
13 a[i] += a[j] * a[i - 1 - j];
14 }
15 return a[n];
16 }
17 };