重复全排列--Educoder

有重复元素的排列问题 Educoder

任务描述

设集合R={r1,r2,…,rn}是要进行排列的n个元素,其中r1,r2,…,rn可能相同。
试着设计一个算法,列出R的所有不同排列。
即,给定n以及待排的n个可能重复的元素。计算输出n个元素的所有不同排列。

输入描述

第1行是元素个数n,1<=n<=500。接下来的1行是待排列的n个元素,元素中间不要加空格。

输出格式

程序运行结束时,将计算输出n个元素的所有不同排列。最后1行中的数是排列总数。

C代码

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>

const int N = 1e6 + 20;
int trie[N][30],id,res;

void Swap(char& a, char& b)
{
	char t = a;
	a = b;
	b = t;
}

void insert(char s[])
{
	int p = s[0] - 'a';
	int u = 0;
	for (int i = 0; s[i]; i++)
	{
		p = s[i] - 'a';
		if (!trie[u][p]) trie[u][p] = ++id;
		u = trie[u][p];
	}	
}

bool chk(char s[])
{
	int p;
	int u = 0;
	for (int i = 0; s[i]; i++)
	{
		p = s[i] - 'a';
		if (trie[u][p]) u = trie[u][p];
		else return false;
	}
	return true;
}

void all_permutation(char s[],int len,int idx)
{
	if (idx > len - 1) return;
	if (idx == len - 1 && !chk(s))
	{
		printf("%s\n", s);
		insert(s);
		res++;
	}
	for (int i = idx; i < len; i++)
	{
		Swap(s[i], s[idx]);
		all_permutation(s, len, idx + 1);
		Swap(s[i], s[idx]);
	}
}

int main()
{
	int n;
	char s[510];
	scanf("%d", &n);
	scanf("%s", s);
	all_permutation(s,n,0);
	printf("%d\n", res);
	return 0;
}

C++

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;

const int N = 1e6 + 20;
int trie[N][30],id,res;


void insert(char s[])
{
	int p = s[0] - 'a';
	int u = 0;
	for (int i = 0; s[i]; i++)
	{
		p = s[i] - 'a';
		if (!trie[u][p]) trie[u][p] = ++id;
		u = trie[u][p];
	}	
}

bool chk(char s[])
{
	int p;
	int u = 0;
	for (int i = 0; s[i]; i++)
	{
		p = s[i] - 'a';
		if (trie[u][p]) u = trie[u][p];
		else return false;
	}
	return true;
}

void all_permutation(char s[],int len,int idx)
{
	if (idx > len - 1) return;
	if (idx == len - 1 && !chk(s))
	{
		printf("%s\n", s);
		insert(s);
		res++;
	}
	for (int i = idx; i < len; i++)
	{
		swap(s[i], s[idx]);
		all_permutation(s, len, idx + 1);
		swap(s[i], s[idx]);
	}
}

int main()
{
	int n;
	char s[510];
	scanf("%d", &n);
	scanf("%s", s);
	all_permutation(s,n,0);
	printf("%d\n", res);
	return 0;
}

注意

因为有重复问腿,所以手搓了一个字典树,在用c++全排列还可以使用next_permutation();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值