forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain5.cpp
More file actions
36 lines (26 loc) · 695 Bytes
/
main5.cpp
File metadata and controls
36 lines (26 loc) · 695 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/// Source : https://leetcode.com/problems/climbing-stairs/description/
/// Author : liuyubobobo
/// Time : 2017-11-20
#include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
/// Fibonacci Number - Closed Formula
/// Fn = 1/sqrt(5) * {[(1+sqrt(5))/2]^n - [(1-sqrt(5))/2]^n}
///
/// Time Complexity: O(logn)
/// Space Complexity: O(1)
class Solution {
public:
int climbStairs(int n) {
assert(n > 0);
if(n == 1)
return 1;
double sqrt5 = sqrt(5.0);
return (int)((pow((1 + sqrt5) / 2, n + 1) - pow((1 - sqrt5) / 2, n + 1)) / sqrt5);
}
};
int main() {
cout << Solution().climbStairs(10) << endl;
return 0;
}