Climbing Stairs

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?

/** 整理的提交代码
 * 处理复杂度为O(n)
 * 主要思路:最简单的方法是使用递归(f(n)=f(n-1)+f(n-2)),但是n较大时效率太低,时间复杂度以O(2n)指数递增。
 * 使用递归的主要问题是:1、函数调用的开销,2、可能的重复计算额外开销,3、可能的调用栈溢出错误。
 * 为了避免重复计算,可以将前面计算的结果保存,如果后面需要则查找之前保存结果。
 * 简单方法是通过从小往大算,其实就是用循环的方法实现递归,但循环变量从小往大增加。
 * 提交结果: 
 * (Judge Small) 
 * Run Status: Accepted! 
 * Program Runtime: 4 milli secs (基本在几毫秒)
 * Progress: 10/10 test cases passed. 
 * (Judge Large) 
 * Run Status: Accepted!
 * Program Runtime: 8 milli secs	(基本稳定在几毫秒左右)
 * Progress: 45/45 test cases passed.
 */
#include <cassert>
#include <iostream>
using namespace std;

class Solution {
public:
	// 如果n太大可能会结果会溢出,可以使用long long。
	int climbStairs(int n) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		if (n == 1)
		{
			return 1;
		}
		if (n == 2)
		{
			return 2;
		}

		int NMinusOne = 2;	// f(n-1)
		int NMinusTwo = 1;	// f(n-2)
		int N;
		for (int i = 3; i <=n; i++)
		{
			N = NMinusOne + NMinusTwo;	// f(n) = f(n-1) + f(n-2)
	
			// 更新f(n-1)和f(n-2)
			NMinusTwo = NMinusOne;
			NMinusOne = N;
		}

		return N;
	}
};

int main()
{
	int n = 0;
	cout << "input stair steps: ";
	cin >> n;
	assert(n != 0);

	Solution s;
	int result = s.climbStairs(n);

	cout << "result: " << result << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值