dfs计算全排列

思路:先在 n 个中选一个, 再在 n-1 中选一个,选出的数保存在 b[] 中

#include <iostream>

using namespace std;

int vis[20];
int a[20] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 };
int b[20];

void dfs(int s, int n)
{
	if (s == n)
	{
		for (int i = 0; i < n; i++)
		{
			cout << b[i] << " ";
		}
		cout << endl;
		return;
	}
	for (int i = 0; i < n; i++)
	{
		if (vis[i] == 0)
		{
			vis[i] = 1;
			b[s] = a[i];
			dfs(s + 1, n);
			vis[i] = 0;
		}
	}
}
int main()
{
	memset(b, 0, sizeof(b));
	memset(vis, 0, sizeof(vis));
	dfs(0, 4);
}