leetcode-96-Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

1
2
3
4
5
6
7
8
9
10
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

we set dp[n] is the number of BST that store n consecutive values
we can get dp[n] as follows:

we set 1 as root node, so left subtree has 0 children, right subtree has n - 1 children, the number of bst is dp[0] * dpn - 1;

we set 2 as root node, so left subtree has 1 children, right subtree has n - 2 children, the number of bst is dp[1] * dp[n - 2];

generally, we set k as root noode, so left subtree has k - 1 children, right subtree has n - k children, the number of bst is dp[k - 1] * dp[n - k];

dp[n] = d[0] dp[n - 1] + … + dp[k - 1] dp[n - k] + … + dp[n - 1] * dp[0];

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1, 0);
dp[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int k = 1; k <= i; ++k) {
dp[i] += dp[k - 1] * dp[i - k];
}
}
return dp[n];
}
};
Donate? comment?