暴力递归法:
int Fibo (int N)
{
if(Fibo(N)=1||Fibo(N)=2)return 1;//如果只有return值就不用写中括号了;
return Fibo(N-1)+Fibo(N-2);
}
这里的时间复杂度为O(n2);
备忘录用法:
备忘录的用法就是先把所有的值都设为0,如果计算出了值,就返回那个值,不用再计算一遍,时间复杂度是O(n)
int helper(vector<int> memo,n) //一看到vector容器就要想到数组,那么后面的n就是数组的长度;
{
if(n==1||n==2) return 1;
if(memo[n]!=0) return memo[n];//后面可以不用写else,因为当不满足这个条件时候会自动跳到下一行
//这里如果fib(n)已经计算过了,就返回已经计算的值,不再继续计算一遍;
memo[n]=helper(memo,n-1)+helper(memo,n-2);
return memo[n];
}
int fib(N){
vector<int> memo(N+1,0);//把数组中全部的值都初始化为0
return helper(memo,N);}