70. Climbing Stairs -- 动态规划、斐波那契数列

来源:互联网 发布:网络程蝶依视频 编辑:程序博客网 时间:2024/05/16 12:41

70. Climbing Stairs – 动态规划、斐波那契数列

解读:
这道题目很有意思,第一种思想可以把它看成斐波那契数列,即现在的值是前两个的值相加。即 n = [n-1] + [n-2].
爬楼梯也是一样,到达第n台阶从[n-1]出发只需要1中方法,从[n-2]出发有两种方法(走两个一步,和一次跨两步)。假设到达n-1的走法有x1种,到达n-2的方法有x2种,那么到达n的方法就有x1+x2种,好吧越来越想不明白了,但是从第一部递推下去的话是这个规律。

二。主要还是看看如何动态规划解决。
什么是动态规划?利用数组记住以前的结果。

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.

解1:斐波那契数列

public int climbStairs(int n) {    // base cases    if(n <= 0) return 0;    if(n == 1) return 1;    if(n == 2) return 2;    int one_step_before = 2;    int two_steps_before = 1;    int all_ways = 0;    for(int i=2; i<n; i++){        all_ways = one_step_before + two_steps_before;        two_steps_before = one_step_before;        one_step_before = all_ways;    }    return all_ways;}
class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        step = []        step.append(0)        step.append(1)        step.append(2)         if n == 0:            return 0        elif n == 1:            return 1        elif n == 2:            return 2        for i in range(3,n+1):            step.append(step[i-1]+step[i-2])        return step[n]
阅读全文
0 0