1. Topics
Given N, how many structurally unique BST 's (binary search trees) that store values 1 ... n?
For example,
Given N = 3, there is a total of 5 unique BST ' s.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
2. Solution
Class Solution {public : int numtrees (int n) { vector<int> num; Num.push_back (1); for (int i=1; i<=n; i++) { num.push_back (0); if (i<3) num[i]=i; else{for (int j=1; j<=i; j + +) num[i]+=num[j-1]*num[i-j];} } return num[n]; } ;
Ideas:
We'll start with the 0 analysis.
0 when there is no one binary search tree without any node is also a case, that is tree[0] = 1
1 when a binary search tree has only one node is also a case, i.e. tree[1] = 1
2 when a binary search tree has 2 nodes, it must have a node as the root node, so the total quantity is, tree[2] = tree[0] * tree[1] + tree[1] * [0]
3 When a binary search tree has 3 nodes, there must be a node as the root node, so the total quantity is, tree[3] = tree[0] * tree[2] + tree[1] * [1] + TREE[2] * [0]
The idea of dynamic planning is used here to save the previously counted in an array.
http://www.waitingfy.com/archives/1617
Leetcode Unique Binary Search Trees