Posted onEdited onInLeetcodeViews: Valine: Symbols count in article: 11kReading time ≈10 mins.
Tree的性质
Divide and Conquer模版
1 2 3 4 5 6 7 8 9 10 11 12
deftraversal(root): # none or leaf ifnot root: # do sth # divide left = traversal(root.left) right = traversal(root.right) # Conquer res = # merge return res
小技巧
T O(n) 一般是遍历所有点 S O(h) 用堆栈来做的话是遍历所有点 O(n) 用队列实现遍历所有点
Posted onEdited onInLeetcodeViews: Valine: Symbols count in article: 2.3kReading time ≈2 mins.
heapq–堆数据结构
heapq模块是python的一个标准库,它实现了一个堆数据结构,堆数据结构是一种二叉树。
什么是堆数据结构?
官网给出的定义是: This implementation uses arrays for which
heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]
for all k, counting elements from zero. 我们可以这样理解: 堆是完全二叉树或者近似二叉树,它的各个节点的键值都有固定对应的的数字,根节点(即root,最上面起始位置)是0,若父节点为heap[k],则子节点为heap[2k+1]和heap[2k+2]。父节点对应的值总是小于或者等于子节点,称为最小堆。对应的,父节点的值总是大于或者等于子节点,称为最大堆。在heapq中,使用的是最小堆。
defbacktracking(self, nums, temp, ans, used): if len(temp) == len(nums): ans.append(list(temp)) for i in range(len(nums)): if used[i] or i>0and nums[i]==nums[i-1] andnot used[i-1]: # 判断条件 continue temp.append(nums[i]) used[i] = True# 记录访问 self.backtracking(nums, temp, ans, used) used[i] = False temp.pop()
defbacktracking(self, nums, temp, res, start): res.append(list(temp)) for i in range(start,len(nums)): temp.append(nums[i]) self.backtracking(nums, temp, res, i+1) temp.pop()
90. Subsets II
因为input含有duplicate,所以在进入backtracking之前需要检查
1 2 3 4 5 6 7 8
defbacktracking(self, nums, temp, res, start): res.append(list(temp)) for i in range(start,len(nums)): if i > start and nums[i] == nums[i-1]: continue temp.append(nums[i]) self.backtracking(nums, temp, res, i+1) temp.pop()
classSolution(object): defcombinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ res = [] self.backtracking(k,n,[],res,1) return res
defbacktracking(self, k, target, temp, res, start): if len(temp) > k: return elif len(temp) == k and target == 0: res.append(list(temp)) else: for i in range(start, 10): temp.append(i) self.backtracking(k, target - i, temp, res, i+1) temp.pop()
Medium
22 Generate Parentheses
recursion rule 就是判断left,right的count啦,直到满足right == n
1 2 3 4 5 6 7
defdfs(self,temp, left, right, res,n): if left < n: self.dfs(temp+'(',left+1,right,res,n) if right < left: self.dfs(temp+')',left, right+1, res,n) if right==n: res.append(temp)
320. Generalized Abbreviation
这道题debug了好久,困惑于如何使得数字和字母不会在base case的时候重复导出
1 2 3 4
4 3d 2r1 2rd ...
1 2 3 4 5 6 7 8 9 10
defbacktrack(res, word, pos, string, count): if pos == len(word): if count>0: string += str(count) res.append(string) else: backtrack(res,word,pos+1,string,count+1) ## 这个track保证了index每次不断加1 从而在base的时候输出,然后每一次count同时加1,为了记录count backtrack(res, word, pos+1, string + (str(count) if count>0else"")+ word[pos], 0) ## 这个是为了退一步,先保存当前的count数字,然后因为数字不能连续,所以+word【index】,同时把count清0