70. Climbing Stairs

来源:互联网 发布:cherry键盘 mac 编辑:程序博客网 时间:2024/05/18 04:00

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 *path=new int[n+1];        path[0]=1;        path[1]=1;        for(int i=2;i<=n;i++)            path[i]=path[i-1]+path[i-2];        return path[n];    }};
class Solution {public:    int climbStairs(int n)     {        int nWays1 = 1, nWays2 = 1, tmp;        for(int i = 2; i <= n; i++)        {            tmp = nWays1;            nWays1 = nWays2;            nWays2 = tmp + nWays2;        }        return nWays2 ;    }};
0 0