Test instructions
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
Ideas:
n = 0 o'clock, empty tree, only one tree. n = 1 o'clock, only one possibility, also 1.
n >= 2 o'clock, the 12....N, respectively, I is the root node, then the left has I-1 nodes, the right side of the n-i-1 node, so
F[n] + = f[k-1]*f[n-k-1], k =,...., n-1
Code:
C++:
Class Solution {public: int numtrees (int n) { int *cnt = new Int[n+1]; Memset (cnt,0, (n+1) *sizeof (int)); Cnt[0] = 1; CNT[1] = 1; for (int i = 2;i <= n;i++) for (int j = 0;j < I;++j) Cnt[i] + = cnt[j]*cnt[i-j-1]; int sum = Cnt[n]; delete []cnt; return sum; }};
Python:
Class solution: # @return An integer def numtrees (self, N): f = [0 for x in range (0,n+1)] f[0] = 1
F[1] = 1 for i in range (2,n+1): for J in Range (0,i): f[i] + = f[j]*f[i-j-1] return f[n]
"Leetcode" Unique Binary Search Trees