leetcode 96: Unique Binary Search Trees java

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.