递归实现数的全排列

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值