leetcode 95 96 解題思路

2021-09-12 15:06:50 字數 2143 閱讀 6357

95. unique binary search trees ii

given an integer n, generate all structurally uniquebst's(binary search trees) that store values 1 ... n.

example:

input:3output:[

[1,null,3,2],

[3,2,null,1],

[3,1,null,null,2],

[2,1,3],

[1,null,2,null,3]

]explanation:the above output corresponds to the 5 unique bst's shown below:

1 3 3 2 1

\ / / / \ \

3 2 1 1 3 2

/ / \ \

2 1 2 3

生成n個節點的所有二叉搜尋樹。這裡跟二叉搜尋樹一樣也是用到了遞迴進行建樹。

/**

* definition for a binary tree node.

* struct treenode

* };

*/class solution

vectorgenerate(int left, int right) //遞迴建立左右子樹

for(int k = left; k <= right; k++) //k為當前對應情況的根節點}}

return res; }};

96. unique binary search trees

given n, how many structurally uniquebst's(binary search trees) that store values 1 ... n?

example:

input:3output:5explanation: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 個節點 可以組合成多少種二叉搜尋樹。

利用迭代, l0 個節點只有一種情況, 1個節點也只有一種情況,2個節點有兩種情況,3個節點有5種情況,即左右子節點分別為 (2,0),(1 ,1)和(0,2)。還需要注意的一點是,求左右子樹所有的個數時根據排列組合原則是相乘的關係。

可以得出規律:  f(0) = 1

f(1) = 1

f(2) = f(1) * f(0) + f(0) * f(1)

f(3) = f(2)*f(0) + f(1)*f(1) + f(0)*f(2)

f(n) = f(n - 1) * f(0) + f(n - 2) * f(1) + ... + f(0) * f(n - 1)

其實這就是 卡特蘭數

Leetcode 95 96 不同的二叉搜尋樹

輸入 3 輸出 1,null,3,2 3,2,null,1 3,1,null,null,2 2,1,3 1,null,2,null,3 解釋 以上的輸出對應以下 5 種不同結構的二叉搜尋樹 1 3 3 2 1 3 2 1 1 3 2 2 1 2 3 給定乙個整數 n,求以 1 n 為節點組成的二叉搜...

LeetCode PlusOne (附帶解題思路)

給定乙個非負整數組成的非空陣列,在該數的基礎上加一,返回乙個新的陣列。最高位數字存放在陣列的首位,陣列中每個元素只儲存乙個數字。你可以假設除了整數 0 之外,這個整數不會以零開頭。示例 1 輸入 1,2,3 輸出 1,2,4 解釋 輸入陣列表示數字 123。示例 2 輸入 4,3,2,1 輸出 4,...

POJ 1171 Letter Game 解題思路

原題鏈結 題目意思大致如下 首先給你乙個可用字符集,比如 prog 那麼我們需要計算的單詞,都是在這個集合內的元素,否則單詞的權值是0 那麼可以組成的單詞rog pog rop等等 計算單詞的最大權值,但是單詞可以拼接起來。但是拼接起來後還是要在可用集合中,且個數都不能超支。下面是題目對用的程式 1...