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?
题目分析:上楼梯问题,每次可上1或2个台阶,求出达到给定的层数有多少种方法。
示例:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
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
注意:这道题不能用递归,会提示超时,所以需要想一个其他办法。
方法一:
- 思路:
(1)如果起始跳一阶的话,剩余的n-1阶就有 f(n-1) 种跳法;
(2)如果起始跳二阶的话,剩余的n-2阶就有 f(n-2) 种跳法;
所以f(n) = f(n-1) + f(n-2),实际结果即为斐波纳契数。
斐波那契数列:n=1–>1;n=2–>2 ;n=3–>n=1的结果+n=2的结果;n=4–>n=2的结果+n=3的结果;n=5–>n=3的结果+n=4的结果… …
↓↓↓递归的写法
def test(num):
if num==1:
return 1
elif num==2:
return 2
else:
return test(num-1)+test(num-2)
num = int(input())
print(test(num))
该题应采用递归的逆向思维,从底层向上算。观察斐波那契数列得出的规律。
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
p,q=1,2
if n<3:
return n
else:
for i in range(n-2):
p,q=q,p+q
return q
另外再给大家看一下我第一次写出来的东西(得出的是过程,这个与题意不符):
x=4
for n in range(10):
for m in range(20):
if n*1+m*2==x:
if n>=1 and m>=1:
print('%d个一和%d个二'%(n,m))