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]; } };
还有一种解法,就是利用矩阵+快速幂,时间复杂度O(logn)。首先,将这个问题转化为矩阵问题。
这样,求就变成了,接下来就是用快速幂的方法解决这个问题。
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]; } };
时间: 2024-10-20 03:33:32