C++实现全排列

#include <iostream>
#include<vector>
#include<string>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <queue>
#include <algorithm>//算法头文件
#include <numeric>
#include <stack>
#include<typeinfo>
#include<regex>
#include<stdio.h>
#include <stdlib.h>
#include <crtdbg.h> 

#include <thread>
//#include<bits/stdc++.h>
using namespace std;

void Perm(int start, int end, vector<int>& arr);
int main()
{
	int n;
	cout << "请输入有多少个元素:";
	cin >> n;
	int a;
	vector<int> arr;
	for (int i = 0; i < n; i++)
	{
		cin >> a;
		arr.push_back(a);
	}
	Perm(0, n, arr);
	return 0;
}
void Perm(int start, int end, vector<int>& arr) //这里相当于递归算法,
{
	//道理start=end时,就相当于这次递归结束,找到了一个排列组合
	if (start == end)
	{
		for (int i = 0; i < end; i++)
		{
			cout << arr[i] << " ";
		}
		cout << endl;
		return;
	}
	for (int i = start; i < end; i++)
	{
		swap(arr[start], arr[i]);//假设3,4,5为例,3P(4,5)是已经一个组合,后面则是4P(3,5),5P(3,4),因此需要交换一下
		Perm(start + 1, end, arr);//相当于P(4,5)
		swap(arr[i], arr[start]);//回溯,把顺序还原,不然就破坏了数据,排列就进行不下去了
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子木呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值