递归实现排列型枚举

// 递归实现排列型枚举
#include
using namespace std;
const int N = 10;
int state[N], n;
bool bis[N];

void dfs(int u)
{
	if (u == n + 1)
	{
		for (int i = 1; i <= n; ++i) 
			cout << state[i] << " \n"[i == n];
		return;
	}

	for (int i = 1; i <= n; ++i)
	{
		if (!bis[i])
		{
			state[u] = i;
			bis[i] = true;
			dfs(u + 1);
			bis[i] = false;
		}
	}
}

int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n;
	dfs(1);
	return 0;
}

你可能感兴趣的:(深度优先,算法)