# House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]        3      / \    2   3      \   \         3   1 Output: 7  Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]            3          / \        4   5      / \   \     1   3   1 Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def rob(self, root: TreeNode) -> int:
def superrob(node):
# returns tuple of size two (now, later)
# now: max money earned if input node is robbed
# later: max money earned if input node is not robbed

# base case
if not node: return (0, 0)

# get values
left, right = superrob(node.left), superrob(node.right)

# rob now
now = node.val + left[1] + right[1]

# rob later
later = max(left) + max(right)

return (now, later)

return max(superrob(root))

# 由爬楼梯问题引发的思考

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.

Method 1: 递归求解

class Solution(object):
def climbStairs(self, n):
if n == 1 or n <= 0:
return 1
return climbStairs(n-1) + climbStairs(n-2)

Method 2: 非递归求解

class Solution(object):
def climbStairs(self, n):
a = b = 1
for x in range(2, n + 1):
a, b = b, a + b
return b

Method 3：通项公式求解

class Solution(object):
def climbStairs(self, n):
sqrt5 = math.sqrt(5)
Phi = (1 + sqrt5) / 2
phi = (1 - sqrt5) / 2
return int((Phi ** (n + 1) - phi ** (n + 1)) / sqrt5)

Method 4: 杨辉三角叠加法

class Solution(object):
def c(self, m, n):
x = 1
for i in xrange(m-n+1, m+1):
x *= i
for i in xrange(2, n+1):
x /= i
return x
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
result = 0
for i in range(0, n/2+1):
result += self.c(n-i, i)
return result