全排列的代码

#include
#include
using namespace std;
const int N = 15;
int a[N], n;
bitset bis;

void dfs(int step)
{
	if (step == n + 1)
	{
		for (int i = 1; i <= n; ++i)
		{
			cout << a[i] << " \n"[n == i];//如果满足n==i则换行
		}
		return;
	}

	for (int i = 1; i <= n; ++i)//满足字典序
	{
		if (bis[i]) continue;
		bis[i] = 1;
		a[step] = i;
		dfs(step + 1);
		//恢复现场
		a[step] = 0;
		bis[i] = 0;
	}
}

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

	return 0;
}

你可能感兴趣的:(算法,c++)