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
1) The total number of structures is not related to the n ordered number stored, that is, the storage is three-way or 5, 6, 9 results are the same; 2) n=0\1, the result is 1;n ordered number, whichever is the root node, the value to the left of the left dial hand tree, the right is the right subtree, in this case, The total number of possible structures is: Left dial hand number of tree structures * Number of right sub-trees, so the original problem is broken down into two sub-problems, 3) to take N ordered number as the root node of the structure of the problem, you can get the solution of the original problem, but it should be noted, such as: 1, 2, 3 take 1 or 3 as the root node, the structure number is the same, That is, it has symmetry, so also consider the parity, 4) can be decomposed into the same sub-problem, you can use recursion, the program uses a cyclic method. */int numtrees (int n) {vector<int> store;store.push_back (1); Store.push_back (1); for (int i=2;i<=n;++i) {int tmp=0;for (int j=0;j<i/2;++j) {tmp+=2*store[i-1-j]*store[j];} if (i%2) tmp+=store[i/2]*store[i/2];store.push_back (TMP);} return store[n];}
Leetcode (+): Unique Binary Search Trees