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

70.Climbing Stairs(法1递归穷举法2动态规划)

时间:2015-02-02 23:15:59      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

You are climbing a stair case. It takes n steps to reachto the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways canyou climb to the top?

HideTags

 Dynamic Programming



#pragma once
#include<iostream>
using namespace std;

//法1:递归穷举,超时
int climbStairs1(int n) {
	if (n == 0)
		return 1;
	else if (n < 0)
		return 0;
	return climbStairs1(n - 1) + climbStairs1(n - 2);
}


//法2:动态规划。最后一步可能为1可能为2,即Ai=Ai-1 + Ai-2,斐波那契
int climbStairs2(int n) {
	if (n < 3)
		return n;
	int n1 = 1;
	int n2 = 2;
	for (int i = 3; i <= n; i+=2)
	{
		n1 = n1 + n2;
		n2 = n1 + n2;//二步长求斐波那契
	}
	if (n%2)
		return n1;
	return n2;
}
void main()
{
	cout << climbStairs2(6) << endl;
	cout << climbStairs1(6) << endl;
	system("pause");
}


70.Climbing Stairs(法1递归穷举法2动态规划)

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43415755

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