基本的なアルゴリズム(4) - 再帰(階乗、フィボナッチ数、バイナリ検索、置換)

再帰:彼らは自分自身を呼び出します。

  • 長所:簡単な手順を理解しやすいです。
  • 短所:スクラッチパッドの真ん中には、それは多くのメモリを必要とします。遅いです。

実施例1、Nの階乗 - (再帰反復)_シンプル

(実施例2)、フィボナッチ数(再帰的に)_シンプル

(実施例3)、二分探索(再帰反復)_ミディアム

(実施例4)、置換(再帰的に)_困難

#include <iostream>
using namespace std;

/*没有终止条件,无限执行的递归
void doA() {
	cout << "hello." << endl;
	doA();
}
*/

//递归 n=n*(n-1)!
long 阶乘(int n) {
	if (n == 0)
		return 1;
	else
		return n * 阶乘(n - 1);
}
//迭代 n=n*(n-1)!
long 阶乘2(int n) {
	long ans = 1;
	for (int i = n; i > 0; i--)
		ans = ans * i;
	return ans;
}
//递归 斐波那契数列0,1,1,2,3,5,8 …
int Fibona(int n) {
    int y;
    if (n <= 1)
      y = n;
    else
      y = Fibona(n - 1) + Fibona(n - 2);
    return y;
}

//迭代的二分查找
int BinarySearch_I(int* a, const int x, const int n) {
	int left = 0, right = n - 1;
	while (left <= right) {
		int mid = (left + right) / 2;
		if (x < a[mid]) right = mid - 1;
		else if (x > a[mid]) left = mid + 1;
		else return mid;
	}
	return -1;
}

//递归的二分查找
int BinarySearch_R(int* a, const int x, const int left,const int right) {
	if (left <= right) {
		int mid = (left + right) / 2;
		if (x < a[mid]) return BinarySearch_R(a, x, left, mid - 1);
		else if (x > a[mid]) return BinarySearch_R(a, x, mid + 1, right);
		else return mid;
	}
	return -1;
}
//递归的排列组合
void Permutations(char* p, const int k, const int m) {
	if (k == m) {
		for (int i = 0; i <= m; i++)
			cout << p[i];
		cout << endl;
	}
	else {
		for (int i = k; i <= m; i++) {
            
			swap(p[k], p[i]);
			Permutations(p, k + 1, m);
			swap(p[k], p[i]);
     /*过程解析
	//a开头的,后面跟着bc的所有排列
	swap(p[0], p[0]);
	Permutations(p, 1, 2);
	swap(p[0], p[0]);
	//b开头的,后面跟着ac的所有排列
	swap(p[0], p[1]);
	Permutations(p, 1, 2);
	swap(p[0], p[1]);
	//c开头的,后面跟着ab的所有排列
	swap(p[0], p[2]);
	Permutations(p, 1, 2);
	swap(p[0], p[2]);
	*/   
		}
	}
}

int main() {
	for (int num = 0; num < 10; num++) {
		cout << "!" << num << "=" << 阶乘(num) << endl;
		cout << "!" << num << "=" << 阶乘2(num) << endl;
	}
    
	cout << Fibona(3) << endl;
    
	int m[] = { 0,1,2,3,4,5,6,7,8 };
	int ans;
	int num = 7;
	if ((ans = BinarySearch_I(m, num,9)) < 0) 
		cout << "not found." << endl;
	else
		cout << "it is found in " << ans << endl;

	if ((ans = BinarySearch_R(m, num, 0, 8)) < 0)
		cout << "not found." << endl;
	else
		cout << "it is found in " << ans << endl;
    
    //排列组合
	char s[] = "abc";
	Permutations(s, 0, 2);//字符串,索引
	system("pause");

	return 0;
}
公開された76元の記事 ウォン称賛30 ビュー5830

おすすめ

転載: blog.csdn.net/weixin_45926367/article/details/104815006