LeetCode OJ:Climbing Stairs

来源:互联网 发布:学校网络机房设计方案 编辑:程序博客网 时间:2024/05/22 08:01

Climbing Stairs

 

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?


class Solution {public:    int climbStairs(int n) {        int a=1,b=1,t;        for(int i=2;i<=n;i++){            t=a;            a=a+b;            b=t;        }        return a;    }};

answer2

数学公式,斐波那契数列通项:

n

n

n

F

2

5

1

2

5

1

5

1

 



class Solution {public:    int climbStairs(int n) {        const double s=sqrt(5);        double a=(1+s)/2;        double b=(1-s)/2;        return floor((pow(a,n+1)+pow(b,n+1))/s+0.5);    }};


n

n

n

F

2

5

1

2

5

1

5

1

 

n

n

n

F

2

5

1

2

5

1

5

1

 

0 0
原创粉丝点击