您的位置:首页 > 其它

【蓝桥杯学习记录】【1】递归与循环(1)从循环到递归

2018-02-06 18:38 459 查看
相似性——递归的关键是发现逻辑相似性    
出  口   ——不要忘记递归出口                

打印 从begin到end 的所有数字 

#include <iostream>
#include <cstdio>
#include <string.h>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#define PI atan(1.0)*4

using namespace std;

/*
递归的关键是发现逻辑相似性    相似性
不要忘记递归出口               出口
*/

void f(int n)//自己写的笨的
{
int a = n;
if(n > 0)
{
n--;
//递归打印0-n的数字
f(n);
}
cout << a << endl;
}

void f_s(int n)//标准的简单的
{
if(n > 0)
f_s(n-1);

cout << n << endl;
}

void f_be (int begin, int end)//打印 从begin到end 的所有数字
{
cout << begin << endl;
if (begin < end)
f_be (begin+1, end);
}

int addall(int a[],int begin)
{

if(a[begin])
{
begin++;
addall(a,begin+1);
}
int x = x + a[begin];//不能这样 因为是要进行一个数 和 一个数组的一部分的和 的 加法

return x;
}

int addall_s(int a[],int begin,int end)
{

//踢皮球 a{    . [. {........] ]     }
if(begin > end)
return 0;
int x = addall_s(a, begin+1,end);
return a[begin] + x;	//向上一次的调用返回本次的begin和后边所有元的值的和
}

int addall_s_f(int a[],int begin,int end)//反向从end开始
{

//踢皮球 a{    [[.........]  . ] .    }
if(end < begin)
return 0;
int x = addall_s_f(a, begin, end-1);
return a[end] + x;	//向上一次的调用返回本次的end和前边所有元的值的和
}
int addall_x(int a[],int begin,int end)//二分 的 递归求和问题
{										//

//踢皮球 二分

if(begin == end) return a[begin];

int mid = (begin + end)/2;
int x = addall_x(a, begin, mid);
int y = addall_x(a, mid+1, end);

return x + y;

//向上一次的调用返回本次的end和前边所有元的值的和
}

bool issamestring(string s1,string s2)
{
if(s1.length()!=s2.length()) return 0;
if(s1.length()==0) return 1;
if(s1[0]!=s2[0]) return 0;
return issamestring(s1.substr(1),s2.substr(1));//http://blog.csdn.net/qq_18815817/article/details/70239460
}													//http://blog.csdn.net/qhs1573/article/details/12236805
//http://bbs.csdn.net/topics/100124317
//
/** strcpy与memcpy以及strncpy **/
//http://blog.csdn.net/gogor/article/details/4511430
/** string 与char* char[]区别及转化 **/
//http://blog.csdn.net/steft/article/details/60126077

int main()
{
//int n;
//cin >> n;
//f(n);//自己写的笨的  打印从0~n的所有数字
//f_s(9);//标准的简单的
//f_be(3,11);//打印 从begin到end 的所有数字

//int a[] = {2,5,3,9,12,7};

//int sum = addall(a,0);
//int sum = addall_s(a,0,5);
//int sum = addall_s_f(a,0,5);

//int sum = addall_x(a,0,5);
//cout << sum << endl;

cout << issamestring("abcd","abcd") << endl; //判断是否是相同的字符串

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  蓝桥杯 c 学习记录