###### tags: `leetcode` `fibonacci`
# 70. Climbing
It is a fibonacci.
## me, use formula solution
```python=
class Solution:
def climbStairs(self, n: int) -> int:
x = 5**0.5/5
c1 = (1+x)
c2 = (1-x)
return round((c1*((1+5*x)/2)**n + c2*((1-5*x)/2)**n)/2)
```
### How to do sqrt() faster?
https://stackoverflow.com/questions/3047012/how-to-perform-square-root-without-using-math-module
> 2**0.5 is pre-calculated, in CPython:
## me, DP
```python=
class Solution:
def climbStairs(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
i = 1
a = [1, 1]
while i < n:
a.append(a[-1] + a[-2])
i += 1
return a[-1]
```
## Solution: Brute Force
$T: n^2$
$S: n^2$
```python=
class Solution:
def climbStairs(self, n: int) -> int:
if n==0:
return 1
if n==1:
return 1
return self.climbStairs(n-1)+self.climbStairs(n-2)
```
## Solution: Recursion with Memoization
## Solution: Markovian chain, O(lgn)
```java=
public class Solution {
public int climbStairs(int n) {
int[][] q = {{1, 1}, {1, 0}};
int[][] res = pow(q, n);
return res[0][0];
}
public int[][] pow(int[][] a, int n) {
int[][] ret = {{1, 0}, {0, 1}};
while (n > 0) {
if ((n & 1) == 1) {
ret = multiply(ret, a);
}
n >>= 1;
a = multiply(a, a);
}
return ret;
}
public int[][] multiply(int[][] a, int[][] b) {
int[][] c = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
}
}
return c;
}
}
```