1384 全排列

本文详细解析了1384全排列问题的算法实现,针对含有重复字符的字符串,介绍了如何通过深度优先搜索(DFS)和字典排序输出所有可能的排列组合。文章提供了完整的C++代码示例,展示了如何避免重复排列,以及如何使用next_permutation函数简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1384 全排列

给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",

输出为:

 

1123

1132

1213

1231

1312

1321

2113

2131

2311

3112

3121

3211

 收起

输入

输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)

输出

输出S所包含的字符组成的所有排列

输入样例

1312

输出样例

1123
1132
1213
1231
1312
1321
2113
2131
2311
3112
3121
3211
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <algorithm>
using namespace std ;
const int MAX= 10005 ;
char str[MAX] ;
int a[MAX] ;
int n ;
int vis[MAX];
int p[MAX];
map<string,int> mp ;
void dfs(int v){
	if(v == n ){
		string s = "" ;
		for(int i = 0 ; i<n ; i++ ){
			s+=p[i]+'0' ;
			//printf("%d",p[i]);
		}
		cout<<s<<endl;
		return ;
	}
	
	for(int i = 0 ; i<n ;i++ ) {
		if(!vis[i]){
			vis[i] = 1 ;
			p[v] = a[i] ;
			dfs(v+1) ;
			vis[i] = 0 ;
			while(i-1<n && a[i] == a[i+1]) i++ ;
		}
	}
	
}
int main(){
	cin >> str ;
	n = strlen(str);
	for(int i = 0 ;i<n ; i++ ) {
		a[i] = str[i]-'0' ;
	}
	sort(a,a+n);
	dfs(0) ;
	
	
	return 0 ;
}
#include<iostream>
#include<algorithm>  
#include<cstdio>  
#include<cstring>
#include<queue>
using namespace std;
main()
{
    char s[1005];
    int len;
    scanf("%s",s);
    len=strlen(s);
    sort(s,s+len);
    do{
        puts(s);
    }while(next_permutation(s,s+len));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值