all permutation of string

/***
9.5 Write a method to compute all permutations of a string.
IDEA: considering a string
start from the begining,
***/

#include<iostream>
#include<vector>
#include<set>
#include<string>

using namespace std;

void permutation(string str, int index, set<string> *strset) {

       if(index < 0) return;

       set<string> ts = *strset;
       strset->clear();
       set<string> :: iterator it;
       string::iterator its;

       for(it = ts.begin(); it != ts.end(); it++) {
              string s = *it;
              for(its = s.begin(); its != s.end(); its++) {         
                     s.insert(its, str[index]);
                     strset->insert(s);
                     s = *it;
              }
              s.push_back(str[index]);
              strset->insert(s);
       }

       permutation(str, index-1, strset);
}

set<string> allpermutation(string str) {
       set<string> permutationset;
       int sz = str.size();
       string s;
       s.push_back(str[sz-1]);
       permutationset.insert(s);
       permutation(str, sz-2, &permutationset);
       return permutationset;
}

void main() {
       string s = "cat";
       set<string> permutationset = allpermutation(s);
       set<string>::iterator it;
       for(it = permutationset.begin(); it != permutationset.end(); it++) {
              cout<<*it<<endl;
       }

}



Solution 2 - solved by backtracking
permutation tree is attached



void swap(char *ch1, char *ch2) {
       char temp = *ch1;
       *ch1 = *ch2;
       *ch2 = temp;
}

void allpermutation(string str, vector<string> *pstrs, int index) {
       // constraints: swap until the end of string
       if (index == 0) {
              pstrs->push_back(str);
              return;
       }

       for(int i = index; i>=0; i--) {
              swap(&str[i], &str[index]);
              allpermutation(str, pstrs, index--);
              //backtracking
              swap(&str[i], &str[index]);
       }

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs