码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode - Climbing Stairs

时间:2014-10-13 23:41:27      阅读:393      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   ar   for   sp   on   问题   

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

bubuko.com,布布扣

bubuko.com,布布扣这样,求bubuko.com,布布扣就变成了bubuko.com,布布扣,接下来就是用快速幂的方法解决这个问题。

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

标签:style   http   color   io   ar   for   sp   on   问题   

原文地址:http://blog.csdn.net/akibatakuya/article/details/40048317

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!