LeetCode - 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?

Solution:

状态转移方程:f(n) = f(n-1)+f(n-2),等等,这不就是斐波那契数列吗?!那我们就用不着数组了。

public int climbStairs(int n) {
    if(n<=1) return n;
    int f1 = 1, f2 = 1;
    for(int i=2; i<=n; i++) {
        int tmp = f2;
        f2 = f2+f1;
        f1 = tmp;
    }
    return f2;
}

 

 

你可能感兴趣的:(LeetCode)