全排列(去重)

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define maxn 1005

using namespace std;
char s[maxn],ans[maxn];
bool book[maxn];
int len,total;
void dfs(int step)
{
	if(step==len)
	{
		cout << ans << endl;
		total++;
		return ;
	}
	for(int i=0;i<len;i++)
	{
		if(book[i]==false)
		{
			int j;
			for(j=i+1;j<len;j++)
			{
				if(book[j]==true&&s[i]==s[j])//如果两字符相同,且位置靠后的已经在前面,则有重复,不符合
					break;
			}
			if(j==len)
			{
				book[i]=true;
				ans[step]=s[i];
				dfs(step+1);
				book[i]=false;
			}
		}
	}
}
int main() 
{
	cin>>s;
	len=strlen(s);
	sort(s,s+len);
	memset(book,false,sizeof(book));
	dfs(0);
	cout << total << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wwwlps/article/details/79545212