leetcode刷题记录(五)


797. All Paths From Source to Target

1
2
3
4
5
6
7
8
def allPathsSourceTarget(self, graph):
def dfs(cur, path):
if cur == len(graph) - 1: res.append(path)
else:
for i in graph[cur]: dfs(i, path + [i])
res = []
dfs(0, [0])
return res

617.Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

1
2
3
4
5
6
7
8
9
10
11
12
13
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 and t2:
root = TreeNode(t1.val+t2.val)
root.left = self.mergeTrees(t1.left,t2.left)
root.right = self.mergeTrees(t1.right,t2.right)
return root
else:
return t1 or t2

728.Self Dividing Numbers

1
2
is_self_dividing = lambda num: '0' not in str(num) and all(num % int(digit) == 0 for digit in str(num))
return filter(is_self_dividing, range(left, right + 1))

Subdomain Visit Count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
visits, res = {}, []
for domain in cpdomains:
tmp = domain.split()
count, doms = int(tmp[0]), tmp[1].split('.')
for i in range(len(doms)):
domain = '.'.join(doms[i:])
if visits.get(domain, 0):
visits[domain] += count
else:
visits[domain] = count
for v in visits.items():
res.append(str(v[1]) + ' ' + v[0])
return res

814.Binary Tree Pruning

1
2
3
4
5
6
7
8
9
class Solution:
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return root
root.left, root.right = self.pruneTree(root.left), self.pruneTree(root.right)
return root if root.val == 1 or root.left or root.right else None

要认真学习啊!
没有买到优衣库的T恤qwq