首页 > 代码库 > 70.Climbing Stairs(法1递归穷举法2动态规划)

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

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动态规划)