递推与递归
递归:函数调用自身的行为叫做递归。
递推:找到前一项与后一项的关系并且清楚其初始条件或者最终结果问题就可以解决问题,这种方法叫做递推。
递推的一般形式:f(n)=a1f(n-1)+a2f(n-2)+...anf(1)+an+1
转:
一般步骤:
1.设函数f(i)的含义
2.从逻辑上寻找f(i)与f(i-1),f(i-2)等等之间的关系
3.写出递推式
4.写出目标f(n)
5.写出初始值(边界)f(0)
6.验证正确性
递推与递归的
相似点:
1.都是把问题拆分成可以解决的子问题
2.一般分析问题的过程一样,写出状态转移方程,临界值。
不同点:
1.递归比递推耗费空间和时间(系统栈)
2.递推要考虑子问题是否已经解决过,递归不用
3.两者只是程序实现上的差别
HDU2044 http://acm.hdu.edu.cn/showproblem.php?pid=2044
我们可以看出,s[i]=s[i-1]+s[i-2];即这是一个斐波那契数列
两种方法:
法一:
1 #include<stdio.h> 2 #include<iostream> 3 #include<algorithm> 4 using namespace std; 5 int main() 6 { 7 int n; 8 cin>>n; 9 long long s[55]; 10 s[0]=1; 11 s[1]=1; 12 for(int i=2;i<=50;i++){ 13 s[i]=s[i-1]+s[i-2]; 14 15 } 16 while(n--){ 17 int a,b; 18 cin>>a>>b; 19 cout<<s[b-a]; 20 } 21 }
法二:
1 #include<stdio.h> 2 #include<string.h> 3 #include<iostream> 4 #include<algorithm> 5 using namespace std; 6 int main() 7 { 8 int a,b,n; 9 long long s[55]; 10 memset(s,0,sizeof(s)); 11 cin>>n; 12 while(n--){ 13 cin>>a>>b; 14 s[a]=1; 15 s[a+1]=1; 16 for(int t=a+2;t<=b;t++){ 17 s[t]=s[t-1]+s[t-2]; 18 } 19 cout<<s[b]<<endl; 20 } 21 }
你若盛开,清风自来...