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

解题思路:这是一个裴波那契数列。

java版本:

public class Solution {
    public int climbStairs(int n) {
       if(n<=2) return n;
       int i=3;
       int s1=1,s2=2,s=0;
       while(++i<=n){
       s=s1+s2;
       s1=s2;
       s2=s;
       }
       return s;
    }
}

c++版本:

class Solution {
public:
    int climbStairs(int n) {
        int step1=1,step2=2,step=0;
        if(n<=2) return n;
        int i=3;
        while(++i<=n){
            step=step1+step2;
            step1=step2;
            step2=step;
        }
        return step;
    }
};

你可能感兴趣的:(LeetCode)