LeetCode OJ 之 Climbing Stairs ( 爬楼梯 )

来源:互联网 发布:怎样设置淘宝客 编辑:程序博客网 时间:2024/05/22 04:55

题目:

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?

总共有n个阶梯,每次可以爬1个或2个阶梯,问有多少种方式爬完楼梯?

思路:

设f(n)表示爬n阶楼梯的不同方法数,为了爬到第n阶楼梯,有两种选择

1、从第n-1阶前进1步;

2、从第n-2阶前进一步;

因此,有f(n) = f(n-1)+ f(n-2)

这是一个斐波那契数列。

可以使用递归,但是太慢,空间复杂度高,这里我们使用迭代。

代码:

class Solution {public:    int climbStairs(int n)     {        int pre=1;        int cur=1;        for(int i=1; i < n ; i++)        {            int tmp=cur;            cur = cur + pre;            pre = tmp;        }        return cur;    }};





0 0
原创粉丝点击