首页 > 代码库 > 全排列dfs算法

全排列dfs算法

如下

#include <iostream>
using namespace std;
#define MAX 10
#define _CRT_SECURE_NO_WARNINGS
int a[MAX], book[MAX], out[MAX], N, Ans;
void dfs(int x){
	//判断退出条件
	if (x > N) {
		++Ans;
		for (int i = 1; i <= N; i++){
			cout << out[i] << " ";
		}
		cout << endl;
		return;
	}
	//当下怎么走
	for (int i = 1; i <= N; i++){
		if (book[i]) continue;
		book[i] = 1;
		out[x] = a[i];		
		dfs(x + 1);
		book[i]= 0;
	}
}
int main(){
	int T;
	freopen("input.txt","r",stdin);
	cin >> T;
	for (int t = 1; t <= T; t++){
		cin >> N;
		for (int i =1; i <= N; i++){
			cin >> a[i];		
		}
		//数据初始化 , Ans, book数组,out数组
		Ans = 0;
		for (int i = 1; i <= N; i++){
			book[i] = out[i] = 0;
		}
		cout << "Case #" << t << endl;
		//递归函数调用
		dfs(1);	

		//输出结果
		cout << Ans << endl;
	}
	
	while (1);
	return 0;
}

 

全排列dfs算法