洛谷 P1706 全排列问题 :STL / dfs

题目描述

输出自然数1到n所有不重复的排列,即n的全排列,要求所产生的任一数字序列中不允许出现重复的数字。

输入输出格式

输入格式:

n(1≤n≤9)

输出格式:

由1~n组成的所有不重复的数字序列,每行一个序列。每个数字保留5个常宽。

输入输出样例

输入样例#1: 
3
输出样例#1: 
    1    2    3
    1    3    2
    2    1    3
    2    3    1
    3    1    2
    3    2    1

思路描述:

第一种:用stl函数库里next_permutation(升序),prev_permutation(降序),头文件:#include<algorithm>

返回值:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int main() {
	int a[1000], n;
	cin >> n;
	for (int i = 1; i <= n; i++)
		a[i] = i;
	 do{
		for (int i = 1; i <= n; i++) {
			printf("%5d", a[i]);
		}
			cout << "
";
	 } while (next_permutation(a + 1, a + n + 1));
	return 0;
}

  第二种:用dfs实现全排列

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int n, a[10], book[10];//a[i]代表第i个数,book标记用没用过,0就没用过
void dfs(int c) {
	if (c == n + 1) {//搜索结束
		for (int i = 1; i <= n; i++)
			printf("%5d", a[i]);
		cout << "
";
		return;
	}
	for (int i = 1; i <= n; i++) {
		if (book[i] == 0) {//若没用过
			a[c] = i;//赋值
			book[i] = 1;//标记
			dfs(c + 1);
			book[i] = 0;//取消标记 回溯
		}
	}
	return;
}
int main() {
	cin >> n;
	dfs(1);
	return 0;
}

  

原文地址:https://www.cnblogs.com/52dxer/p/10369955.html