Description:
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
Note:
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:
Analysis and Thinking:
題目要求在輸入n值的情況下,得出有多少種結構唯一的1~n的二叉查找樹。這裏我們採取了一種簡便的方法,就是基於公式原理得出解,其中,我們引用catalan數公式(式子爲:)。對於n個節點,將其中第j個節點設爲根節點,得出左子樹j-1個節點,右子樹i-j個節點,左右子樹相乘可得到結果。
Steps:
1.設置外層循環,用i記錄,從2~n進行循環
2.設置內存循環,對於每一層i值,將j從1遍歷到i
3.內循環中,將j設置爲根節點,相應的左右子樹分別有j-1以及i-j個節點,左右子樹的種樹相乘,就是當前以j爲根節點得出的二叉搜索數總的數量
4.對j從1求和到j,對i從2遍歷至n,得出n對於的二叉查找樹數量
Codes:
class Solution {
public:
int numTrees(int n) {
vector<int> record(n + 1, 0);
record[0] = 1;
record[1] = 1;
for(int i = 2; i <= n; i++)
for(int j = 1; j <= i; j++)
{
record[i] =record[i]+record[i - j]*record[j - 1];
}
return record[n];
}
};
Results: