發表文章

[ LeetCode ] 337. House Robber III

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution ( object ) : def rob ( self , root ) : """ :type root: TreeNode :rtype: int """ res = [ 0 ] d = {} def dfs ( node ) : if not node : return 0 if node in d : return d[ node ] col_1 = dfs( node .left) + dfs( node .right) col_2 = node .val if node .left : col_2 += dfs( node .left.left) + dfs( node .left.right) if node .right : col_2 += dfs( node .right.left) + dfs( node .right.right) d[ node ] = max (col_1 , col_2) return max (col_1 , col_2) return dfs( root )

String Summary

151 .  Reverse Words in a String     def reverseWords_02(self, s):         """         :type s: str         :rtype: str         """         def revS(start, end):             while start < end:                 s[start], s[end] = s[end], s[start]                 start, end = start + 1, end - 1         s = s.strip()         s = list(s)         space = 0         count = 0         for i in range(len(s)):             if s[i] == " " and space < 1:     ...

Array Summary

Use two pointer as array's benefice   Use hash table may reduce the time complexity from O(n^2) to O(n log n)   832 .  Flipping an Image class Solution(object):     def flipAndInvertImage(self, A):         """         :type A: List[List[int]]         :rtype: List[List[int]]         """         if not A:             return []         for i in range(len(A)):             A[i] = A[i][::-1]             for j in range(len(A)):                 A[i][j] = 1 ^ A[i][j]         ret...

Python note

[Check object attributes] For example, if forget what attributes I can use for "random". use command dir() dir(random) >>> dir(random) [..., ' randint ', 'random', ' randrange ', 'sample', 'seed', 'setstate', ' shuffle ',...] >>> [Random] random. randint(a, b) Return a random integer N such that a <= N <= b. e.g. random.randint(0,3) return 0 or 1 or 2 or 3 random. randrange(start, stop[, step]) Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object. e.g. random.randrange(0,3) return 0 or 1 or 2  [Copy]  There are essentially three kinds of 'function calls': Pass by value Pass by reference Pass by object reference Python is a PASS-BY-OBJECT-REFERENCE programming language. shallow copy vs deep copy default copy is "shallow copy" b...