字符反转递归
#include<bits/stdc++.h>
using namespace std;
int sum(int a[],int start){
if(start==9) return a[start];
return a[start]+sum(a,start+1);
}
string fan(string s,int end){
if(end<0) return "";
return fan(s.substr(1),end-1)+s[0];
}
int fibo(int n){
if(n==1||n==2)
return 1;
return fibo(n-1)+fibo(n-2);
}
int main()
{
int a[10]={0};
for(int i=1;i<10;i++)
a[i]=i;
cout<<sum(a,0)<<endl;
string s="iloveyou";
cout<<fan(s,s.length()-1)<<endl;
cout<<fibo(3)<<endl;
return 0;
}
fibo递归andfor循环
#include<bits/stdc++.h>
using namespace std;
int fibo(int n)
{
if(n==1||n==2)
return 1;
return fibo(n-1)+fibo(n-2);
}
int n[10000];
int main()
{
n[1]=n[2]=1;
int a;
cin>>a;
cout<<fibo(a)<<endl;
for(int i=3;i<=a;i++)
{
n[i]=n[i-1]+n[i-2];
}
cout<<n[a]<<endl;
return 0;
}
汉诺塔
#include<bits/stdc++.h>
using namespace std;
void HanoiTower(int N,string from,string to,string help){
if(N==1){
cout<<"move"<<N<<from<<"->"<<to<<endl;
return;
}
HanoiTower(N-1,from,help,to);
cout<<"move"<<N<<from<<"->"<<to<<endl;
HanoiTower(N-1,help,to,from);
}
int main()
{
int a;
string from,to,help;
cin>>a>>from>>to>>help;
HanoiTower(a,from,to,help);
return 0;
}
二分查找递归and非递归
#include<bits/stdc++.h>
using namespace std;
int find(int n[],int lefe,int right,int temp){
if(lefe>=right){
if(lefe==right)
return lefe;
return -1;
}
int mid=(lefe+right)>>1;
if(n[mid]>=temp){
find(n,lefe,mid,temp);
}
else if(n[mid]<temp){
find(n,mid+1,right,temp);
}
}
int find1(int n[],int lefe,int right,int temp){
if(lefe>=right){
if(lefe==right)
return lefe;
return -1;
}
int mid=(right+lefe+1)>>1;
if(n[mid]<=temp){
find1(n,mid,right,temp);
}
else if(n[mid]>temp){
find1(n,lefe,mid-1,temp);
}
else return lefe;
}
int main()
{
srand((unsigned)time(NULL));
int n[110];
for(int i=0;i<110;i++){
n[i]=i+rand()%10+1;
}
sort(n,n+110);
for(int i=0;i<8;i++){
cout<<n[i]<<" ";
}
cout<<endl;
int temp;
cin>>temp;
cout<<find(n,0,109,temp)<<endl;
cout<<find1(n,0,109,temp)<<endl;
int l=0,r=109;
while(l<r){
int mid=(l+r)>>1;
if(n[mid]>=temp){
r=mid;
}
else
l=mid+1;
}
cout<<l<<endl;
l=0,r=109;
while(l<r){
int mid=(l+r+1)>>1;
if(n[mid]<=temp){
l=mid;
}
else
r=mid-1;
}
cout<<l<<endl;
return 0;
}
最小公倍数最大公约数
#include<iostream>
using namespace std;
typedef long long LL;
LL lcm(LL a,LL b)
{
return a%b==0?b:lcm(b,a%b);
}
int main()
{
LL a,b,c;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
LL temp=a*b/lcm(a,b);
cout<<temp<<endl;
return 0;
}
总结:大问题转换小问题,不改变问题本质,找边界,找变化。
|