Python程序计算到达第n个楼梯的方式
有n个楼梯,站在底部的人想爬到顶部。此人一次可以爬 1 个楼梯或 2 个楼梯。数一数路数,人能登顶。
考虑图中所示的示例。 n 的值为 3。有 3 种方法可以到达顶部。该图取自 Easier Fibonacci 谜题
Python3
# A program to count the number of ways to reach n'th stair
# Recurssive program to find n'th fibonacci number
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# returns no. of ways to reach s'th stair
def countWays(s):
return fib(s + 1)
# Driver program
s = 4
print ("Number of ways =",countWays(s))
# Contributed by Harshit Agrawal
Python3
# A program to count the number of ways to reach n'th stair
# Recursive function used by countWays
def countWaysUtil(n, m):
if n <= 1:
return n
res = 0
i = 1
while i<= m and i<= n:
res = res + countWaysUtil(n-i, m)
i = i + 1
return res
# Returns number of ways to reach s'th stair
def countWays(s, m):
return countWaysUtil(s + 1, m)
# Driver program
s, m = 4, 2
print ("Number of ways =", countWays(s, m))
# Contributed by Harshit Agrawal
Python3
# A program to count the number of ways to reach n'th stair
# Recursive function used by countWays
def countWaysUtil(n, m):
res = [0 for x in range(n)] # Creates list res with all elements 0
res[0], res[1] = 1, 1
for i in range(2, n):
j = 1
while j<= m and j<= i:
res[i] = res[i] + res[i-j]
j = j + 1
return res[n-1]
# Returns number of ways to reach s'th stair
def countWays(s, m):
return countWaysUtil(s + 1, m)
# Driver Program
s, m = 4, 2
print ("Number of ways =", countWays(s, m))
# Contributed by Harshit Agrawal
输出:
Number of ways = 5
上述实现的时间复杂度是指数级的(黄金比例提高到 n 次方)。可以使用前面讨论的斐波那契函数优化来优化它以在 O(Logn) 时间内工作。
Python3
# A program to count the number of ways to reach n'th stair
# Recursive function used by countWays
def countWaysUtil(n, m):
if n <= 1:
return n
res = 0
i = 1
while i<= m and i<= n:
res = res + countWaysUtil(n-i, m)
i = i + 1
return res
# Returns number of ways to reach s'th stair
def countWays(s, m):
return countWaysUtil(s + 1, m)
# Driver program
s, m = 4, 2
print ("Number of ways =", countWays(s, m))
# Contributed by Harshit Agrawal
输出:
Number of ways = 5
Python3
# A program to count the number of ways to reach n'th stair
# Recursive function used by countWays
def countWaysUtil(n, m):
res = [0 for x in range(n)] # Creates list res with all elements 0
res[0], res[1] = 1, 1
for i in range(2, n):
j = 1
while j<= m and j<= i:
res[i] = res[i] + res[i-j]
j = j + 1
return res[n-1]
# Returns number of ways to reach s'th stair
def countWays(s, m):
return countWaysUtil(s + 1, m)
# Driver Program
s, m = 4, 2
print ("Number of ways =", countWays(s, m))
# Contributed by Harshit Agrawal
输出:
Number of ways = 5
有关详细信息,请参阅有关到达第 n 级楼梯的计数方式的完整文章!