forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
163.cpp
85 lines (71 loc) · 1.94 KB
/
163.cpp
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
78
79
80
81
82
83
// C++ program to print all permutations
// with repetition of characters
#include <bits/stdc++.h>
#include<string.h>
using namespace std;
/* Following function is used by
the library qsort() function
to sort an array of chars */
int compare (const void * a, const void * b);
/* The main function that recursively
prints all repeated permutations of
the given string. It uses data[] to store all
permutations one by one */
void allLexicographicRecur (char *str, char* data,
int last, int index)
{
int i, len = strlen(str);
// One by one fix all characters at
// the given index and recur for
// the/ subsequent indexes
for ( i = 0; i < len; i++ )
{
// Fix the ith character at index
// and if this is not the last
// index then recursively call
// for higher indexes
data[index] = str[i] ;
// If this is the last index then
// print the string stored in
// data[]
if (index == last)
cout << data << endl;
else // Recur for higher indexes
allLexicographicRecur (str, data, last, index+1);
}
}
/* This function sorts input string,
allocate memory for data (needed
for allLexicographicRecur()) and
calls allLexicographicRecur() for
printing all permutations */
void allLexicographic(char *str)
{
int len = strlen (str) ;
// Create a temp array that will
// be used by allLexicographicRecur()
char *data = (char *) malloc (sizeof(char) * (len + 1)) ;
data[len] = '\0';
// Sort the input string so that
// we get all output strings in
// lexicographically sorted order
qsort(str, len, sizeof(char), compare);
// Now print all permutaions
allLexicographicRecur (str, data, len-1, 0);
// Free data to avoid memory leak
free(data);
}
// Needed for library function qsort()
int compare (const void * a, const void * b)
{
return ( *(char *)a - *(char *)b );
}
// Driver code
int main()
{
char str[] = "ABC";
cout << "All permutations with repetition of "<<
str <<" are: "<<endl ;
allLexicographic(str);
return 0;
}