Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 71d869d

Browse files
Update README.md
1 parent e5531d2 commit 71d869d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

‎README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5547,6 +5547,30 @@ class Solution:
55475547
- 由于递推关系式可知第 `N` 行的第 `K` 个数计算自第 `N - 1` 行的第 `(K + 1) // 2` 个数
55485548
- 我们称第 `N` 行的第 `K` 个数为C,第 `N - 1` 行的第 `(K + 1) // 2` 个数为 P
55495549
- `0 → 01`,`1 → 10`,可见变换后实际上是在原来的数字后加了相对的数(这里称 0 与 1 相对),那么如果 K 为奇数则 `C = P`,否则 `C = P 的相对数`
5550+
#### [95. 不同的二叉搜索树 II](https://leetcode-cn.com/problems/unique-binary-search-trees-ii/)
5551+
```python
5552+
# Definition for a binary tree node.
5553+
class TreeNode:
5554+
def __init__(self, x, l=None, r=None):
5555+
self.val = x
5556+
self.left = l
5557+
self.right = r
5558+
5559+
class Solution:
5560+
def generateTrees(self, n: int) -> List[TreeNode]:
5561+
def gen(num):
5562+
if not num: yield None
5563+
for i, n in enumerate(num):
5564+
for l in gen(num[:i]):
5565+
for r in gen(num[i + 1:]):
5566+
yield TreeNode(n, l, r)
5567+
5568+
return bool(n) * [*gen([*range(1, 1 + n)])]
5569+
```
5570+
- 构建递归生成器 `gen`,输入是一系列升序的数字,返回这些数字可能构成的所有二叉树结构
5571+
- 首先,所有数字都有可能作为根,因此遍历 `num` 作为根
5572+
- 根据二叉搜索树的特性(左子树所有节点小于根,右子树大于),可知根的左子树由比根小的数字构成,递归 `num[:i]` 就是左子树所有的可能结构,同理可获得右子树所有可能的结构
5573+
- 左右递归结果的笛卡尔积 + `root`,即为整棵树所有可能的结构
55505574

55515575
# 常用技巧总结
55525576
- set 中的 in 操作时间复杂度为 O(1)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /