[LeetCode OJ]Unique Binary Search Trees
2014-11-05 20:57
267 查看
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
设U(1, 2, ..., n)代表存储1...n的binary search tree的数目。dp(i, n-1)代表以i为根,包含n-1个子结点的二叉树数目。
U(1, 2, ..., n) = dp(1, n-1) + dp(2, n-1) + ... dp(n, n-1).
Clearly, dp(i, n-1) = U(1, 2, ..., i-1) * U(i+1, i+2, ..., n),
and U(i+1, i+2, ..., n) = U(1, 2, ..., n-i).
Thus, dp(i, n-1) = U(1, 2, ..., i-1) * U(1, 2, ..., n-i).
不妨简记U(n) = U(1, 2, ..., n), 那么
U(n) = U(0)*U(n-1) + U(1)*U(n-2) + ... + U(i-1)*U(n-i) + ... + U(n-1)*U(0), 1 <= i <=n.
Example.
U(0) = 1
U(1) = 1
U(2) = dp(1, 1)+dp(2, 1) = U(0)*U(1) + U(1)*U(0) = 2
U(3) = dp(1, 2)+dp(2, 2)+dp(3, 2) = U(0)*U(2) + U(1)*U(1) + U(2)*U(0) = 2 + 1 + 2 = 5
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
设U(1, 2, ..., n)代表存储1...n的binary search tree的数目。dp(i, n-1)代表以i为根,包含n-1个子结点的二叉树数目。
U(1, 2, ..., n) = dp(1, n-1) + dp(2, n-1) + ... dp(n, n-1).
Clearly, dp(i, n-1) = U(1, 2, ..., i-1) * U(i+1, i+2, ..., n),
and U(i+1, i+2, ..., n) = U(1, 2, ..., n-i).
Thus, dp(i, n-1) = U(1, 2, ..., i-1) * U(1, 2, ..., n-i).
不妨简记U(n) = U(1, 2, ..., n), 那么
U(n) = U(0)*U(n-1) + U(1)*U(n-2) + ... + U(i-1)*U(n-i) + ... + U(n-1)*U(0), 1 <= i <=n.
Example.
U(0) = 1
U(1) = 1
U(2) = dp(1, 1)+dp(2, 1) = U(0)*U(1) + U(1)*U(0) = 2
U(3) = dp(1, 2)+dp(2, 2)+dp(3, 2) = U(0)*U(2) + U(1)*U(1) + U(2)*U(0) = 2 + 1 + 2 = 5
class Solution { public: int numTrees(int n) { vector<int> num(n+1, 0); num[0] = 1; for(int i = 1; i <= n; i++) { for(int j = 0; j < i; j++) num[i] += num[j] * num[i - j - 1]; } return num ; } };
相关文章推荐
- LeetCode OJ 之 Unique Binary Search Trees II (不同的二叉搜索树 - 二)
- 【LeetCode OJ】Unique Binary Search Trees
- LeetCode OJ:Unique Binary Search Trees
- LeetCode OJ 95. Unique Binary Search Trees II
- LeetCode OJ:Unique Binary Search Trees II
- LeetCode OJ——Unique Binary Search Trees II
- LeetCode OJ :Unique Binary Search Trees II(唯一二叉搜索树)
- LeetCode OJ:Unique Binary Search Trees(唯一二叉搜索树)
- LeetCode OJ - Unique Binary Search Trees II
- LeetCode OJ——Unique Binary Search Trees
- [leetcode]Unique Binary Search Trees @ Python
- [LeetCode]95.Unique Binary Search Trees II
- 【Leetcode】Unique Binary Search Trees
- [leetcode]Unique Binary Search Trees II @ Python
- Unique Binary Search Trees II
- LeetCode: Unique Binary Search Trees II [096]
- Unique Binary Search Trees -LeetCode
- LeetCode:Unique Binary Search Trees
- Unique Binary Search Trees
- [leetcode] Unique Binary Search Trees