Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 18 additions & 50 deletions Permutations.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,31 @@

using namespace std;

// Checking whether a map has all the values equal to 0 in its key-value mapping
bool isEmpty(map<char,int>m)
{
for(auto y=m.begin();y!=m.end();y++)
{
if(y->second==0)
continue;

else
return false;
}

return true;
}


void perm(map<char,int>freq,string r="")
{
// Checking if all the letters have been exhausted and no further Permutations can be formed
if(isEmpty(freq))
{
cout<<r;
return;
}

// Traversing through all the letters of the string and then Recursively Generating the Permutations
for(auto p=freq.begin();p!=freq.end();p++)
{
// If the Present Letter has already been exhausted, then do not add it and skip this specific iteration of the loop
if(p->second==0)
continue;

// Time Complexity:O(N!);

// Making a duplicate Map containing the frequency of all the letters as it is in the present map but the particular character,pointed in this specific Iteration of the Loop has Frequency less by 1 than found in the original map
map<char,int>temp;

for(auto y=freq.begin();y!=freq.end();y++)
temp[y->first]=y->second;

temp[p->first]--;

// Space Complexity:O(N)

// N=(length of string)

// Recursively calling the function with the newly formed map
perm(temp,r+p->first);
}
}

// Driver Code to test the Function
int main() {
void print_permutation(string permutation,string result){

string s="abaaa";
map<char,int>m;
if(permutation.size()==0)cout<<result;

for(char g:s)
m[g]++;
for(int i=0;i<permutation.size();++i)
//Here What I did is just picked up a specific character from permutation appended to result and then removed that character from permutation
//This Process continues till permutation string is null

print_permutation(permutation.substr(0,i)+permutation.substr(i+1,perutation.size()),result+permutation[i]);

perm(m);
}

return 0;
main(){

string premutation="Hacktoberfest";

print_permutation(permutation,"");

}