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?
//第一种解法class Solution {public: int climbStairs(int n) {int ans[100] = {1,2};for (int i = 2; i < n; i++){ans[i] = ans[i-1] + ans[i-2];}return ans[n-1]; }};
Another solution is to use matrix + Rapid power and time complexity O (logn ). First, convert this problem into a matrix problem.
In this way, the problem is solved by using a quick power method.
class Matrix{public:Matrix();~Matrix();Matrix operator *(const Matrix &t);Matrix& operator=(const Matrix &t);int map[2][2];};Matrix::Matrix(){map[0][0] = 1;map[0][1] = 1;map[1][0] = 1;map[1][1] = 0;}Matrix Matrix::operator*(const Matrix &t){Matrix ans; ans.map[0][0] = (map[0][0]*t.map[0][0]+map[0][1]*t.map[1][0]); ans.map[0][1] = (map[0][0]*t.map[0][1]+map[0][1]*t.map[1][1]); ans.map[1][0] = (map[1][0]*t.map[0][0]+map[1][1]*t.map[1][0]); ans.map[1][1] = (map[1][0]*t.map[0][1]+map[1][1]*t.map[1][1]); return ans; }Matrix& Matrix::operator=(const Matrix &t){for(int i = 0; i <= 1; ++i) { for(int j = 0; j <= 1; ++j) { map[i][j] = t.map[i][j]; } } return *this; }Matrix::~Matrix(){}class Solution {public: int climbStairs(int n) {Matrix res,k;n = n + 1;while(n){if(n & 1) res = res * k;k = k * k;n >>= 1;}return res.map[1][1]; }};
Leetcode-climbing stairs