題目:
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個節點,可能的unique BST 爲DP(n)。跟節點可以是任意一個元素,如第i個元素。根節點左側爲1~i-1個元素,右側爲第i+1到第n個元素。而左側又是一個 i-1 個數的一個子樹可以以任意一個0~i-1 的數字爲根節點。所以左右子樹的可能爲DP(i-1)*DP(n-i)種可能。所以每個DP(n) 用前面的DP的值計算得來。而每個DP又循環每個值作爲根相加。
DP(0) = 1; DP(1) = 1;
代碼如下:
class Solution {
public:
int numTrees(int n) {
int DP[n+1];
DP[0] = 1;
DP[1] = 1;
for(int i = 2; i <= n; ++i){
DP[i] = 0;
}
for(int i = 2; i <= n; ++i){
for(int j = 1; j <=i; ++j){
DP[i] += DP[j-1] * DP[i-j];
}
}
return DP[n];
}
};
注意DP中的元素初始化爲0,以爲後面要累加。