【算法进阶指南】【递归】递归实现排列型枚举

用递归来实现全排列问题:

全排列就是假设1~3的全排列就为:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

可以看出假设本来只有三个位置 __ __ __
首先选择一个1(要保证字典序)
1 __ __
下一个位置只需要保证不再是1即可
就这样一直回溯就能得到最终结果
详细递归过程请参考:这篇

结合代码分析:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <string>

#define ll long long 
#define mod 1e9 + 7
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
#define IOS ios::sync_with_stdio(false);

using namespace std;

int n;
int a[20], book[20];

void dfs(int x)
{
	if(x == n + 1) // 到达最后一个位置
	{
		for(int i = 1; i <= n; i ++) cout << a[i] << " "; // 输出此时答案
		cout << endl;
		return ;
	}
	
	for(int i = 1; i <= n; i ++)
	{
		if(!book[i]) // 这个数没选
		{
			a[x] = i; // 记录选了那些数
			book[i] = 1; // 标记不能在用这个数
			dfs(x + 1); // 下一个位置
			book[i] = 0; // 回溯
		}
	}
}

int main()
{
	cin >> n;
	dfs(1);
	
	return 0;	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值