Leetcode 70. 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?

Note: Given n will be a positive integer.

分析

很简单的动态规划,通过分析能够得到,F(n)=F(n-1)+F(n-2)。然后通过简单的数组迭代就能得到结果。当然也可以利用Fibonacci数列的简便

int climbStairs(int n) {
    if(n==0||n==1)return 1;
    int a[1000000];
    a[0]=1;
    a[1]=1;
    for(int i=2;i<=n;i++)
    {
        a[i]=a[i-1]+a[i-2];
    }
    return a[n];
}

你可能感兴趣的:(Leetcode 70. Climbing Stairs)