首页 > 代码库 > leetcode - Climbing Stairs

leetcode - Climbing Stairs

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)。首先,将这个问题转化为矩阵问题。

    \begin{equation*}    \begin{split}        \begin{bmatrix}            F_{n-1} & F_{n-2}\\            F_{n-2} & F_{n-3}        \end{bmatrix}        \cdot        \begin{bmatrix}            1 & 1\\            1 & 0        \end{bmatrix}        &=        \begin{bmatrix}            F_{n-1}+F_{n-2} & F_{n-2}+F_{n-3}\\            F_{n-2}+F_{n-3} & F_{n-2}        \end{bmatrix}\\        &=        \begin{bmatrix}            F_{n} & F_{n-1}\\            F_{n-1} & F_{n-2}        \end{bmatrix}\\    \end{split}    \end{equation*}

        \begin{bmatrix}            F_{n+1} & F_{n}\\            F_{n} & F_{n-1}        \end{bmatrix}=        \begin{bmatrix}            1 & 1\\            1 & 0        \end{bmatrix}^{n}这样,求F_n就变成了\begin{bmatrix}            1 & 1\\            1 & 0        \end{bmatrix}^{n},接下来就是用快速幂的方法解决这个问题。

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