題目:
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,尋找按照從1到n的二叉搜索樹共有多少顆。
我們都知道二叉搜索樹按照中序遍歷後得到一個從小到大的序列,對於這道題目來說便是一個從1到n的序列。由於最近剛學了動態規劃,這才便嘗試用動態規劃的思想來解決一下這個題目。
從1到n的所有二叉搜索樹,那麼每個結點都有可能是根節點。若我們選中第i個結點爲根節點的話,那麼它的左子樹中序遍歷後必衛1到i-1,那麼它的右子樹中序遍歷後也必會得到i+1到n這樣一個序列。我們只須找出從1到i-1共有多少顆二叉搜索樹f(i-1)再找出i+1到n-1共有多少顆二叉搜索樹。那麼f(i)=f(i-1)*f(n-i)。
而f(n)也即所有點位根節點得到的結果的和f(n)=f(0)*f(n-1)+f(1)*f(n-2)+...+f(n-1)*f(0)
一種c++的實現方法如下:
#include<iostream>
using namespace std;
class Solution {
public:
int numTrees(int n) {
int res[n+1];
res[0] = 1;
for(int i = 1; i <= n; i++) res[i] = 0;
for(int i = 1; i <= n; i++) {
if(i <= 2) {
res[i] = i;
continue;
}
for(int j = 1; j <= i; j++) {
res[i] += res[j-1]*res[i-j];
}
}
int result = res[n];
return result;
}
};