標籤:
96: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
查了下,這個題要用卡特蘭數 參考了這個部落格也沒看明白:http://www.cnblogs.com/springfor/p/3884009.html
然後看了三哥的一個視頻講解:https://www.youtube.com/watch?v=UfA_v0VmiDg
所以拋開卡特蘭數,大思想是動態規劃。找出遞推公式。
思路就是:反正就是BST,每個元素都做根節點,算出每個元素做根節點時有幾種情況,然後每個節點的幾種情況相加。
每個元素有幾種情況,根據bst的特性,就是中序便利是排序的。所以:
以n=3為例。建立一個int res[]= int[3+1](迴圈1,2,3,每個數字對應所再index,而不是1對應0index,2對應1 index...)
1是根節點的時候,1的左子樹是0個,右子樹是2,3(兩個)。所以是1是根節點的種類數是:res[0]乘以res[2]情況數。
2是根節點的時候,2的左子樹是1(1個),右子樹是1(1個)。所以是2是根節點的種類數是:res[1]乘以res[1]情況數。
3是根節點的時候,3的左子樹是1,2(2個),右子樹是(0個)。所以是2是根節點的種類數是:res[2]乘以res[0]情況數。
1 public class Solution { 2 public int numTrees(int n) { 3 if(n ==0 || n ==1) return 1; 4 int res[] =new int[n+1]; 5 res[0]=1; 6 for(int i =1 ; i <= n ; i++){ 7 for(int j = 0; j < i; j++){ 8 res[i] += res[j]*res[i-j-1]; 9 }10 }11 return res[n];12 }13 }
res[0]是有0個數的時候。
res[1]是有1個數的時候。
。。。。
leetcode 96: Unique Binary Search Trees java