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
Basic ideas:
The composition of the tree is selected as the root of the node.
All the elements on the left side of the node will make up the left subtree of the root node.
And all elements on the right will make up the right subtree of the node.
The number of different binary trees with this element as the root is the different number of different numbers of Zuozi * right subtree.
The recursive type is:
Dp[i] =∑dp[j] * dp[I-1-j] 0<=j<i
Class Solution {public: int numtrees (int n) { vector<int> dp (n+1); Dp[0] = 1; DP[1] = 1; for (int i=2, i<=n; i++) {for (int j=0; j<i; j + +) Dp[i] + = dp[j] * dp[i-1-j]; } return dp[n];} ;
Unique Binary Search Trees--Leetcode