16-两种方法全排列

链接:https://www.nowcoder.net/acm/contest/76/H
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制: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;
}

  

转载于:https://www.cnblogs.com/zhumengdexiaobai/p/8443526.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值