Find saddle point
1 2 3 4 5
| count = 0 for i in xrange(1, len(A)-1): for j in xrange(1, len(A[0])-1): if A[i][j] is saddle_point: count+=1
|
DFS
Find the maximum distinct nodes along the binary tree path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def helper(T, prefix, max): if T == None: return max if T.left is None and T.right is None: if len(set(prefix))> max: max = len(set(prefix)) prefix.pop() prefix.append(T.x) helper(T.left, prefix) helper(T.right, prefix) def solution(T): prefix = [] max = 0 helper(T, prefix, max)
|
Greedy
Monkey 过河 A
is the river, D is the step for one jump
A[i] = t
means the stone in the i
position is available at time t
A[i] = -1
means i
position will never have stone.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def solution(A, D): pos = -1 N = len(A) t = 0 while t < max(A): old_pos = pos if (pos+D)>=N: break while pos < N: if A[pos+D]<t and A[pos+D]!=-1: pos+=D if pos == old_pos: break t+=1 return t
|