#include <iostream>
using namespace std;
//递归实现数的全排列
void Permutations(int *a,const int start,const int end )//start和end分别是a的起始位置和终点位置
{
if (start == end)
{
for (int j = 0; j <= end; j++)
cout << a[j] << " ";
cout << endl;
}
else
{
for (int i = start; i <= end; i++)
{
swap(a[start], a[i]);//让a[i]成为首项,刚开始i=start
Permutations(a, start + 1, end);//继续交换a[start+1]和之后的元素
swap(a[start], a[i]);//每次递归完将数据交换回来
}
}
}
//算法解释:比如1 2 3
//循环
//第一个数为1 然后递归:循环
// 第二个数为2 再递归一次:由于start = end不进入循环,输出
// 第二个数为3 再递归一次:由于start = end不进入循环,输出
//第二个数为2 同理.....
//第三个数为3 同理.....
int main()
{
int a[] = { 1, 2, 3 };
Permutations(a, 0, 2);
system("pause");
return 0;
}
递归实现数的全排列
最新推荐文章于 2022-04-25 21:52:50 发布