Basic algorithm (4) - recursion (factorial, Fibonacci number, binary search, permutations)

Recursive: they call themselves.

  • Advantages: easy to understand, simple procedures.
  • Cons: the middle of the scratchpad, it requires a lot of memory. Slow.

Example 1, the factorial of n - (recursive and iterative) _ simple

Example 2, Fibonacci number (recursively) _ simple

Example 3, binary search (recursive and iterative) _ Medium

Example 4, permutations (recursively) _ difficult

#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;
}
Published 76 original articles · won praise 30 · views 5830

Guess you like

Origin blog.csdn.net/weixin_45926367/article/details/104815006