递归函数: 自己调用自己
- 基础部分:由f(n)直接定义,不用递归就能求解
- 递归部分:右侧 f 有一个参数小于n,因此重复利用递归部分即可把右侧 f 的表达式转变为基础部分
示例:
- 【排序方法】我们常常要从n个不同元素的所有排序中确定一个最佳排序。设计一个函数生成 list[k:m] 的所有排序。
#include <iostream>
#include <algorithm> // has copy
#include <iterator>
using namespace std;
template<class T>
void permutations(T list[], int k, int m)
{// 输出 list[k:m] 的所有排序.
// 假定 k <= m.
int i;
if (k == m) {// list[k:m] 只有一个元素, 则直接输出
copy(list, list+m+1,
ostream_iterator<T>(cout, ""));
cout << endl;
}
else // list[k:m] 有不止一个元素
// 生成这些递归
for (i = k; i <= m; i++)
{
swap(list[k], list[i]); //令 list[k]与 list[i]交换位置
permutations(list, k+1, m); //递归
swap(list[k], list[i]); //令 list[k]与 list[i]换回原来位置
}
}
int main()
{
char a[] = {'1', '2', '3', '4'};
cout << "The permutations of 1 are" << endl;
permutations(a, 0, 0);
cout << "The permutations of 123 are" << endl;
permutations(a, 0, 2);
return 0;
}
输出结果:
The permutations of 1 are
1
The permutations of 123 are
123
132
213
231
321
312
- 【子集生成方法】编写一个C++递归函数,输出n个元素的所有子集。例如,三元素集{a,b,c}的子集是{}(空集),{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c}。这些子集用0/1组成的代码序列来表示分别是000,100,010,001,110,101,011,111(0表示相应的元素不在子集中,1表示相应的元素在子集中)。因此你的程序输出长度为n的0/1序列即可。
#include <iostream>
using namespace std;
void f(int *mark, int n, int i)
{ //a为集合元素,mark为标记数组,n为起点,i为元素个数
if (n == i)
{//若只有一个元素,则直接输出
cout << "{";
for (int k = 0; k < i; k++)
cout << mark[k];
cout << "}" << endl;
return;
}
mark[n] = 0;
f(mark, n + 1, i);
mark[n] = 1;
f(mark, n + 1, i);
}
int main()
{
int mark[3];
cout << "The subset of the mark[3] are:" << endl;
f(mark, 0, 3);
return 0;
}
输出结果:
The subset of the mark[3] are:
{000}
{001}
{010}
{011}
{100}
{101}
{110}
{111}