【藍橋杯學習記錄】【1】遞歸與循環(1)從循環到遞歸

相似性——遞歸的關鍵是發現邏輯相似性    

出  口   ——不要忘記遞歸出口                

打印 從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;
}

















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章