Leetcode Climbing Stairs

OpenSoucre發表於2014-06-22

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?

熟悉斐波那契數列的一看就知道斐波那契數列是0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

其通項是f[k] = f[k-1]+f[k-2],k>=2

其中f[0] = 0, f[1] = 1;

而此題類似斐波那契數但初始值有點不同

f[0] = 0, f[1]= 1, f[2] = 2, 對其迭代就行

int climbStairs(int n){
    if(n == 0 || n == 1 || n == 2) return n;
    int stepOne = 1, stepTwo = 2, result = 0;
    for(int i = 3; i <= n ; ++ i){
        result = stepOne + stepTwo;
        stepOne = stepTwo;
        stepTwo = result;
    }
    return result;
}

 

相關文章