链接:https://www.nowcoder.net/acm/contest/76/H
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
老李见和尚赢了自己的酒,但是自己还舍不得,所以就耍起了赖皮,对和尚说,光武不行,再来点文的,你给我说出来1-8的全排序,我就让你喝,这次绝不耍你,你能帮帮和尚么?
输入描述:
无
输出描述:
1~8的全排列,按照全排列的顺序输出,每行结尾无空格。
示例1
输入
No_Input
输出
Full arrangement of 1~8
备注:
1~3的全排列 :
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
dfs:
#include <iostream>
using namespace std;
int d[105]; //存放排列的数字
int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
void dfs(int r, int n){ //r: 已经填的位数;n:总共需要填的位数。
if(r == n){
for(int i = 0; i < n - 1; i++)
cout << d[i] << " ";
cout << d[n - 1] << endl;
}
for(int i = 1; i <= n; i++){ //依次检测1~n是否都填了,没有就填上
int flag = 1;
for(int j = 0; j < r; j++){
if(d[j] == i)
flag = 0;
}
if(flag){
d[r] = i;
dfs(r + 1, n);
}
}
}
int main(){
int n = 8;
dfs(0, n);
return 0;
}
next_permutation(a, a + n, cmp);
#include <iostream>
#include <algorithm>
using namespace std;
int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int main(){
int n = 8;
do{
for(int i = 0; i < n - 1; i++)
cout << a[i] << " ";
cout << a[n - 1] << endl;
}while(next_permutation(a, a + n));
return 0;
}
可去重:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3;
char str[N];
char buf[N];
int toal, len;
bool visit[N];
void pre(int num){
if(num == len){
// cout << buf << endl;
for(int i = 0; i < len - 1; i++){
cout << buf[i] << " ";
}
cout << buf[len - 1];
cout << endl;
toal++;
return ;
}
for(int i = 0; i < len; i++){
if(!visit[i]){
bool flag = 1;
for(int j = i + 1; j < len; j++){
if(visit[j] && str[j] == str[i]){ //检测重复
flag = 0;
break;
}
}
if(flag){
buf[num] = str[i]; //这里不能写成:buf[num++] = str[i];因为for循环没有结束还要用num,不能改变num的值
visit[i] = 1;
pre(num + 1);
visit[i] = 0;
}
}
}
}
int main(){
// cin >> str;
for(int i = 0; i < 8; i++)
str[i] = '1' + i;
len = strlen(str);
sort(str, str + len);
pre(0);
// cout << "toal: " << toal << endl;
return 0;
}