[LeetCode] Unique Binary Search Trees
2014-05-22 15:41
337 查看
题目:
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的结果与n-1的结果是相关联的,首先直观给出计算公式:以n=3为例,f(3)=0*2+1*1+2*0,看出来规律了吗?
我们可以这么想,n从2变成3,即多了一个点,可以把这个点当做根节点,那么根节点引出左右两个孩子,左孩子可以是2/1/0个节点,相应右孩子则为0/1/2个节点,那么总情况数就是左孩子节点个数的情况数×右孩子节点个数的情况数加和。
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
解答:
class Solution { public: int numTrees(int n) { vector<int> num; num.push_back(1); num.push_back(1); if(n == 0) { return num[0]; } else if(n == 1) { return num[1]; } else { for(int j = 2; j <= n; j ++) { int sum = 0; for(int i = 0; i < j; i++) { sum = sum + num[i] * num[j - i - 1]; } num.push_back(sum); } } return num ; } };
思路:
n的结果与n-1的结果是相关联的,首先直观给出计算公式:以n=3为例,f(3)=0*2+1*1+2*0,看出来规律了吗?
我们可以这么想,n从2变成3,即多了一个点,可以把这个点当做根节点,那么根节点引出左右两个孩子,左孩子可以是2/1/0个节点,相应右孩子则为0/1/2个节点,那么总情况数就是左孩子节点个数的情况数×右孩子节点个数的情况数加和。
相关文章推荐
- 【LeetCode】Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- Leetcode 树 Unique Binary Search Trees
- LeetCode题解——Unique Binary Search Trees II
- Leetcode 树 Unique Binary Search TreesII
- Unique Binary Search Trees [LEETCODE]
- [LeetCode]题解(python):096-Unique Binary Search Trees
- LeetCode 096 Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- Unique Binary Search Trees - LeetCode 96
- leetcode Unique Binary Search Trees II
- LeetCode:Unique Binary Search Trees(一维DP)
- LeetCode之Unique Binary Search Trees
- Unique Binary Search Trees - Leetcode
- leetcode — unique-binary-search-trees-ii
- [LeetCode]Unique Binary Search Trees
- Leetcode-Unique Binary Search Trees II
- Leetcode---Unique Binary Search Trees II
- 【LeetCode】【Python题解】Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees(!!DP)