[LeetCode]题解(python):070-Climbing Stairs

题目来源:

  https://leetcode.com/problems/climbing-stairs/


题意分析:

  爬楼梯,一次可以爬一步或者两步。如果要爬n层,问一共有多少种爬法。比如说,如果是3层,可以有[[1,1,1],[1,2],[2,1]]共3种方法。


题目思路:

  这是一个典型的动态规划问题。n层的方法数 = n - 1层的方法数 + n - 2层的方法数。


代码(Python):

  

 1 class Solution(object):
 2     def climbStairs(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         if n == 1 or n == 0:
 8             return 1
 9         i,tmp1,tmp2 = 2,1,1
10         while i <= n:
11             tmp1 = tmp1 + tmp2
12             if i == n:
13                 return tmp1
14             i += 1
15             tmp2 = tmp1 + tmp2
16             if i == n:
17                 return tmp2
18             i += 1
View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/5045540.html

原文地址:https://www.cnblogs.com/chruny/p/5045540.html