学习笔记
| # | Title | Solutions |
|---|---|---|
| 70 | climbing-stairs | 递归(Go,Py) |
| 22 | generate-parentheses | 递归(Go,Py) |
| 226 | invert-binary-tree | 递归(Go,Py),队列(Go) |
| 98 | validate-binary-search-tree | 递归(Go,Py),中序遍历(Go,Py) |
| 104 | maximum-depth-of-binary-tree | 递归(Go) |
| 111 | minimum-depth-of-binary-tree | 递归(Go,Py),层序遍历(Go,Py) |
| 236 | lowest-common-ancestor-of-a-binary-tree | 递归(Go,Py),遍历记录父节点(Go,Py) |
| 297 | serialize-and-deserialize-binary-tree | 层序遍历(Go,Py),递归前序遍历(Go,Py) |
| 105 | construct-binary-tree-from-preorder-and-inorder-traversal | 递归(Go,Py) |
| 77 | combinations | 递归(Go,Py) |
| 46 | permutations | 递归(Go,Py) |
| 47 | permutations-ii | 递归(Go,Py) |
| 50 | powx_n | 递归(Go,Py) |
| 78 | subsets | 递归(Go,Py) |
| 169 | majority-element | 哈希表(Go,Py),计数投票(Go,Py) |
| 17 | letter-combinations-of-a-phone-number | 递归(Go,Py) |
| 51 | n-queens | 回溯(Go,Py) |
题解
70. climbing-stairs
除了递推外也可以用递归,不过涉及到重复计算,需要用哈希表做缓存
22. generate-parentheses
递归
226. invert-binary-tree
- 递归
- 队列
98. validate-binary-search-tree
- 递归
- 中序遍历
111. minimum-depth-of-binary-tree
- 递归
- 使用队列逐层遍历
236. lowest-common-ancestor-of-a-binary-tree
- 递归
- 如果root是p或q,则最近公共祖先就是root
- 后续遍历
- 如果left和right都有找到,那就是root
- 如果left没找到,那返回right(right可能时nil);right没找到亦然
- 建2个哈希表,一个记录父节点,另一个记录是否访问过
297. serialize-and-deserialize-binary-tree/
- 使用队列层序遍历
- 递归前序遍历
297. construct-binary-tree-from-preorder-and-inorder-traversal
- 递归
- 前序遍历的第一个元素为root
- 在中序遍历中找到root的index,从而得出左右子树的长度
- 递归左右子树
77. combinations
- 递归
- 提前建立一个长度为k的空数组
- 递归每次填一个数
- 第k个即为结果
46. permutations
- 递归+回溯
- 提前建立一个长度为k的空数组,并建立一个同样长度为k的空数组用于标识是否已被使用
- 递归每次填一个数
- 第k个即为结果
47. permutations-ii
- 递归+回溯
- 提前建立一个长度为k的空数组,并建立一个字典记录当前每个元素剩余的个数
- 递归每次填一个数
- 第k个即为结果
50. powx-n
- 递归
- n为0时返回1
- n<0时:n=-n,x = 1/x
78. subsets
- 递归
169. majority-element
- 哈希表:遍历记录每个元素出现的次数,大于len(nums)/2即为众数
- 计数投票:用一个整数变量count做计数,遇到众数+1,非众数-1,最后count必定大于0,对应的candidate即为众数
17. letter-combinations-of-a-phone-number
- 递归
51. n-queens
- 回溯