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?

Link:
https://leetcode.com/problems/climbing-stairs/
Analysis:
当n=1时,ans=1;
当n=2时,ans=2;
当n=k时,可以将问题简化为先走一步后面k-1步有ans(k-1)中方法和先走两步后面k-2步有ans(k-2)种方法,即ans(k-1)+ans(k-2)种方法。
Source Code(C++):

#include <iostream>
using namespace std;

class Solution {
public:
    int climbStairs(int n) {
        int a=1, b=2;
        if (n<1) {
            return 0;
        }
        else if (n==1) {
            return a;
        }
        else if (n==2) {
            return b;
        }
        else {
            for(int i=3; i<n; i++) {
                b = a+b;
                a = b-a;
            }
            return a+b;
        }
    }
};


int main() {
    Solution sol;
    cout << sol.climbStairs(27);
    return 0;
}

你可能感兴趣的:(70. Climbing Stairs)