70. Climbing Stairs
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.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
分析:一开始以为是排列组合问题,而且也的确可以列出结果的式子。但是运算量太大了,于是按照前几个结果排列一下,发现是斐波那契数列,那就用数组解决。
代码:
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
if n == 2:
return 2
fib = [1, 2]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib[n-1]
100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
分析:用递归的方法就可以判断。同时对两棵树进行遍历,然后用逻辑与,只有全部相等才是真,否则就算只有一处不同也为假。
代码:
class Solution:
def isSameTree(self, p, q):
if p == None and q == None:
return True
if p != None and q != None:
if p.val == q.val:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return False