Leetcode 96. Unique Binary Search Trees
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
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
Solution #1 Dynamic Programming
Time:
Space:
核心思想是动态规划,但是空间复杂度可以优化到
1, 2, ..., n
中,如果当i
作为根节点时,可以构建的BST有dp[i - 1] * dp[n - i]
个。可以参见下图。
The key idea is Dynamic Programming, however, the algorithm could be optimized to a
Suppose dp[n]
represent the number of unique BST’s that store the sequence 1, 2, ..., n
.
Given a sequence 1, 2, 3, 4, 5
, if 2
becomes the root node, then 1
will on its left side, and 3, 4, 5
will on its right side. And both subsequence 1
and 3, 4, 5
can form their own unique BST’s. Obviously, the number of BST’s that subsequence 1
can constructs is dp[1]
. Moreover, the number of BST’s that the subsequence 3, 4, 5
can constructs is exactly dp[3]
, because 3, 4, 5
has same ordering as 1, 2, 3
. Therefore, we can have following equation:
where n
the size of the sequence.
Thereby, we can get dp[n]
by utilizing following equation:
for(int i = 1; i <= n; i++)
dp[n] += dp[i - 1] * dp[n - i];
What’s more, based on the mirror property, we only need to calculate half of the sequence, and then double it.
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1, 1);
for(int i = 2; i <= n; i++) {
int cnt = 0;
for(int j = 1; j <= i / 2; j++)
cnt += dp[j - 1] * dp[i - j];
if(i % 2 == 1)
dp[i] = 2 * cnt + dp[i / 2] * dp[i / 2];
else
dp[i] = 2 * cnt;
}
return dp[n];
}
};