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
The first is to use recursion to solve, but see the label is DP problem, think about, the number of BST, 0 ~ k-1 can be divided into two intervals, and then can be generated BST, so K of the number of BST is equal to K left and right can be divided into BST the sum of the flight, the amount, a bit around the mouth amount, The code is a little clearer, look at the code:
1 classSolution {2 Public:3 intNumtrees (intN) {4vector<int>ret;5 if(n = =0)return 0;6Ret.reserve (n +1);7ret[0] =1;8 for(inti =1; I <= N; ++i) {9 if(I <3){TenRet[i] =i; One Continue; A } - for(intj =0; J < I; ++j) { -Ret[i] + = ret[j] * ret[i-j-1]; the } - } - returnRet[n]; - } +};
Leetcode oj:unique binary search Trees (unique binary searching tree)