-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution2.cpp
33 lines (31 loc) · 933 Bytes
/
Solution2.cpp
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
class Solution {
public:
int climbStairs(int n) {
vector<vector<long long>> a = {{1, 1}, {1, 0}};
return pow(a, n - 1)[0][0];
}
private:
vector<vector<long long>> mul(vector<vector<long long>>& a, vector<vector<long long>>& b) {
int m = a.size(), n = b[0].size();
vector<vector<long long>> res(m, vector<long long>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 0; k < a[0].size(); ++k) {
res[i][j] += a[i][k] * b[k][j];
}
}
}
return res;
}
vector<vector<long long>> pow(vector<vector<long long>>& a, int n) {
vector<vector<long long>> res = {{1, 1}, {0, 0}};
while (n) {
if (n & 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
};