递归:自己调用自己。
- 优点:容易理解,程序简洁。
- 缺点:中间的结果暂存,需要大量内存。速度慢。
例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;
}