Sunday, August 18, 2013

string permutation

/* 8_4 Write a method to compute all permutations of a string. */

void permutations(string s, bool * b, string word, set<string> & ss) {
    if (s.size() == word.size()) {
        ss.insert(word);
        return;
    }
    for (int i = 0; i < s.size(); ++i) {
        if (!b[i]) {
            b[i] = true;
            word.append(s.substr(i, 1));
            permutations(s, b, word, ss);
            word.erase(word.size()-1);
            b[i] = false;
        }
    }
}

void allPermutation(string s) {
    set<string> ss;
    set<string>::iterator it;
    bool * b = new bool[s.size()-1];
    permutations(s, b, "", ss);
    for (it = ss.begin(); it != ss.end(); it++) {
        cout << *it << endl;
    }
    delete [] b;
   

}

No comments:

Post a Comment