Leetcode NO.96 Unique Binary Search Trees
2015-02-17 03:50
302 查看
本题题目要求如下:
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.
本题比较悲催。。我两个月前第一遍做出来了。这次反倒没做出来
太可悲了。希望能通过写博客能够真正的理清一些题的思路吧。。。不废话了,开始讲算法。
我们首先要明白当n=3时,如何用一个普遍的方法得到上面那5种可能性。
看第2,3组,都是root->left是当n=2的两种可能,root->right是当n=0的一种可能,2*1 = 2;看第四组,就是root->left是n=1的一种可能,root->right是n=1的一种可能,1*1 = 1;看第1,5组,root->left是n=0的一种可能,root->right是n=2的两种可能,1*2 = 2
由此可以得到一个普遍的公式:dp(3) = dp(0)*dp(2) + dp(1)*dp(1)+dp(2)*dp(0)。
再将公式推广到dp(n),即可得到本题的解。
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
本题比较悲催。。我两个月前第一遍做出来了。这次反倒没做出来
太可悲了。希望能通过写博客能够真正的理清一些题的思路吧。。。不废话了,开始讲算法。
我们首先要明白当n=3时,如何用一个普遍的方法得到上面那5种可能性。
看第2,3组,都是root->left是当n=2的两种可能,root->right是当n=0的一种可能,2*1 = 2;看第四组,就是root->left是n=1的一种可能,root->right是n=1的一种可能,1*1 = 1;看第1,5组,root->left是n=0的一种可能,root->right是n=2的两种可能,1*2 = 2
由此可以得到一个普遍的公式:dp(3) = dp(0)*dp(2) + dp(1)*dp(1)+dp(2)*dp(0)。
再将公式推广到dp(n),即可得到本题的解。
class Solution { public: int numTrees(int n) { int res = 0; vector<int> dp(n+1, 0); 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 ; } };
相关文章推荐
- LeetCode No.96 Unique Binary Search Trees
- 《leetCode》:Unique Binary Search Trees
- leetcode之Unique Binary Search Trees
- 【LeetCode】Unique Binary Search Trees
- [C++]LeetCode: 92 Unique Binary Search Trees II
- LeetCode--Unique Binary Search Trees
- Leetcode:unique_binary_search_trees
- Leetcode: Unique Binary Search Trees II
- Leetcode108: Unique Binary Search Trees II
- Leetcode-Unique Binary Search Trees II
- 【LeetCode】【Python题解】Unique Binary Search Trees
- LeetCode 95. Unique Binary Search Trees II
- [LeetCode]Unique Binary Search Trees I&II
- [LeetCode]Unique Binary Search Trees II
- [LeetCode] Unique Binary Search Trees II
- leetcode Unique Binary Search Trees II java
- LeetCode(96) Unique Binary Search Trees
- [Leetcode 75] 96 Unique Binary Search Trees
- LeetCode095 Unique Binary Search Trees II
- 【LEETCODE】95-Unique Binary Search Trees II