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.
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
近期评论