leetcode

题目链接

解题思路:
就是斐波那契数列的应用.

f[ 1 ] = 1

f[ 2 ] = 2

f[ n ] = f[ n - 1 ] + f[ n - 2 ] (n >= 3)

#include <iostream>

using namespace std;

class Solution {
public:
    int climbStairs(int n) {
        int ans = 1;
        int f[ 2 ] = {1, 1};
        for (int i = 2; i <= n; i++) {
            ans = f[ 0 ] + f[ 1 ];
            f[ 0 ] = f[ 1 ];
            f[ 1 ] = ans;
        }
        return ans;
    }
};


int main() {
    Solution solution;
    int N, result;
    cin >> N;
    result = solution.climbStairs(N);
    cout << result << endl;
    return 0;
}