【LeetCode】 70. 爬楼梯--简单递归的应用

版权声明:made by YYT https://blog.csdn.net/qq_37621506/article/details/83063425

简单递归

C++
通过找规律发现后面数字等于前面两项之和
于是通过简单递归写出程序如下

#include <iostream>
using namespace std;
int ds(int n){
	if(n==0)
		return 0;
	else if (n==1)
		return 1;
	else if(n==2)
		return 2;
	else
	return ds(n-1)+ds(n-2);//递归
}
int main(){
	int n;
	while(cin>>n)
	{
		cout<<ds(n)<<endl;
	}
	return 0;
}

程序执行没有问题,但是时间超过限制
利用vector改进,将计算好的结果存储起来,方便调用,不用每次运行都计算一遍

#include <iostream>
#include <vector>
using namespace std;
int ds(int n){
	vector<int>ds(n+1);//定义vector向量
	ds[0]=0;
	ds[1]=1;
	ds[2]=2;
	for(int i=3;i<=n;i++){
		ds[i]=ds[i-1]+ds[i-2];
	}
	return ds[n];
}
int main(){
	int n;
	while(cin>>n)
	{
		cout<<ds(n)<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37621506/article/details/83063425
今日推荐