19,468
社区成员
发帖
与我相关
我的任务
分享
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int i,j;
int L;
int filer(char *p) {
if ((strstr(p, "12") || strstr(p, "21")) //v1v2相邻,但有先后顺序如v1v2或v2v1
&& ((strstr(p,"345") || strstr(p,"543")))) //v3v4v5需要v4在中间不变,v3和v5可以交换,即也有两种排列,v3v4v5或v5v4v3
return 1;
else
return 0;
}
void main() {
L=6;
vector<char> P(L+1);
vector<char>::iterator b,e;
b=P.begin();
e=P.end();
e--;
for (i=0;i<L;i++) P[i]='0'+i+1;
P[L]=0;
i=0;
do {
if (filer(&P[0])) printf("%2d: %s\n",++i,&P[0]);
} while (next_permutation(b,e));
printf("The total: %d\n",i);
}
// 1: 123456
// 2: 125436
// 3: 126345
// 4: 126543
// 5: 213456
// 6: 215436
// 7: 216345
// 8: 216543
// 9: 345126
//10: 345216
//11: 345612
//12: 345621
//13: 543126
//14: 543216
//15: 543612
//16: 543621
//17: 612345
//18: 612543
//19: 621345
//20: 621543
//21: 634512
//22: 634521
//23: 654312
//24: 654321
//The total: 24
//
//qplw.cpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int v=0;
int w=0;
int m;//记录字符串长度
int n;//记录字符串中的字符种类数
char map[256];//记录是哪几种字符
int count[256];//记录每种字符有多少个
int stack[1000];//递归用的栈,并记录当前生成的排列
void Make_Map(char *str) {//统计字符串的相关信息
int s[256];
int i;
memset(s,0,sizeof(s));
memset(count,0,sizeof(count));
m=strlen(str);
if (w<1 || m<w) w=m;
while(*str) {
s[*str]++;
str++;
}
n=0;
for (i=0;i<256;i++)
if (s[i]) {
map[n]=i;
count[n]=s[i];
n++;
}
}
void Find(int depth) {//递归式回溯法生成全排列
if (depth==w) {
int i;
for (i=0;i<depth;i++) putchar(map[stack[i]]);
putchar('\n');
} else {
int i;
if (v && depth>0) {
for (i=0;i<depth;i++) putchar(map[stack[i]]);
putchar('\n');
}
for (i=0;i<n;i++)
if (count[i]) {
stack[depth]=i;
count[i]--;
Find(depth+1);
count[i]++;
}
}
}
void main(int argc,char**argv) {
if (argc<2) {
printf("%s 要产生全排列的字符串 [限定长度|-1]\n",argv[0]);
return;
}
if (argc>=3) w=atoi(argv[2]);
if (-1==w) v=1;
Make_Map(argv[1]);
Find(0);
}
//C:\test>qplw
//qplw 要产生全排列的字符串 [限定长度|-1]
//
//C:\test>qplw 123
//123
//132
//213
//231
//312
//321
//
//C:\test>qplw 123 2
//12
//13
//21
//23
//31
//32
//
//C:\test>qplw 122333 3
//122
//123
//132
//133
//212
//213
//221
//223
//231
//232
//233
//312
//313
//321
//322
//323
//331
//332
//333
//
//C:\test>qplw 123 -1
//1
//12
//123
//13
//132
//2
//21
//213
//23
//231
//3
//31
//312
//32
//321
//