LeetCode OJ-70. Climbing Stairs(爬楼梯问题)

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?


分治法用递归很容易理解,但超时。直接递推也可以,不过要注意好前一项和前两项的位置。
int climbStairs(int n) {
    if (n <= 0) {
        return 0;
    }
    
    int first = 0;
    int second = 1;
    int fn;
    int i;
    for (i = 1; i <= n; ++i) {
        fn = first + second;
        first = second;
        second = fn;
    }
    
    return fn;
}


你可能感兴趣的:(OJ)