全排列dfs算法
Posted wujixing909
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了全排列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算法的主要内容,如果未能解决你的问题,请参考以下文章