pku 1731 Orders
简单的不重复排列问题
//法1 让脚标i自加消重复
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAX 205
char str[MAX],out[MAX];
int len;
bool used[MAX];
void dfs(int cur)
{
if(cur==len)
{
printf("%s\n",out);
}
else
for(int i=0; i<len; i++)
{
if(!used[i])
{
out[cur]=str[i];
used[i]=true;
dfs(cur+1);
used[i]=false;
i++;
while( i<len && str[i]==str[i-1])
i++;
i--;
}
}
}
int main()
{
while(scanf("%s",str)!=EOF)
{
len=strlen(str);
memset(used,false,sizeof(used));
sort(str,str+len);
dfs(0);
}
return 0;
}
//****************************************************
//法2 某牛的hash做法
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define SIZE 100
#define HASHSIZE 26
int len;
char str[SIZE];
char out[SIZE];
int hash[HASHSIZE];
void DFS(int cur)
{
if(cur == len)
{
out[cur] = 0;
printf("%s\n", out);
}
else
{
for(int i = 0; i < HASHSIZE; i++)
{
if(hash[i] > 0)
{
out[cur] = 'a' + i;
hash[i] --;
DFS(cur + 1);
hash[i] ++;
}
}
}
}
int main()
{
while(scanf("%s", str) != EOF)
{
getchar();
memset(hash, 0, sizeof(hash));
int i;
len = strlen(str);
for(i = 0; i < len; i++)
{
hash[str[i] - 'a'] ++;
}
DFS(0);
}
return 0;
}
把一堆相同的字母都放在一个相同的hash[]里,当for(int i = 0; i < HASHSIZE; i++)这句i自加是,就跳过了这堆相同的字母了,比第一种方法更巧,更快...
浙公网安备 33010602011771号