【LeetCode】70. Climbing Stairs

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?

递推公式为f(n)=f(n-1)+f(n-2)

每个元素仅依赖于前两个元素。

class Solution {
public:
    int climbStairs(int n) {
        int step1 = 1;  //0 stair
        int step2 = 1;  //1 stair
        for(int i = 2; i <= n; i ++)
        {
            int nextstep = step1 + step2;
            step1 = step2;
            step2 = nextstep;
        }
        return step2;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4026545.html