-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPermuteLexicographically.txt
77 lines (68 loc) · 1.3 KB
/
PermuteLexicographically.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
How to permute a string and print in lexicographically order?
Things to remember:
1 Sort the string; // necessary to get LEXICOGRAPHICALLY
2 keep sorted string in an arry and use it for getting characters in sorted form
3 Dont send copy of use[] arry .... Send its pointer, because we need to know waht has been used ... try pen & paper to know how
it works
CODE:// similar to anagram ques of karumanchi
#include <iostream>
#include <algorithm>
#include <string.h>
#include<string>
using namespace std;
void permute(char *p, int depth , char *st , bool *use)
{
static int count=0;
int l=strlen(st);
if(depth== l)
{
cout<< count++<<"\t";printf("%s\n",p);
return;
}
int i=0;
for(i=0;i<l;i++)
{
if(!use[i])
{
use[i]=true; //it is very neccessary TO USE SAME use[] ARRAY
p[depth]=st[i];
permute(p,depth+1,st,use);
use[i]=false;
}
}
}
int main() {
char s[]="ABGS"; // for "ABGS" there are 4*3*2*1 = 4! = 24 orders.
int l=strlen(s),i=0;
bool use[l+2];
for(i=0;i<l+2;i++)
use[i]=false;
char p[l+2];
permute(p,0,s,use);
return 0;
}
OUTPUT:
0 ABGS
1 ABSG
2 AGBS
3 AGSB
4 ASBG
5 ASGB
6 BAGS
7 BASG
8 BGAS
9 BGSA
10 BSAG
11 BSGA
12 GABS
13 GASB
14 GBAS
15 GBSA
16 GSAB
17 GSBA
18 SABG
19 SAGB
20 SBAG
21 SBGA
22 SGAB
23 SGBA