"Arrangement of Strings" in "Swords Offer"

Topic description


Enter a string and print out all permutations of the characters in the string lexicographically. For example, if the string abc is input, all strings abc, acb, bac, bca, cab and cba that can be arranged by the characters a, b, and c are printed out.

Code


class Solution {

public:
    vector<string> permutation;
    set<string> permutationSet;

    vector<string> Permutation(string str) {
        if (str.size() != 0)
        {
            int nSize = str.size();
            Permutation(str, nSize, 0);
        }
        for (set<string>::iterator iter = permutationSet.begin(); iter != permutationSet.end(); ++iter)
        {
            permutation.push_back(*iter);
        }
        return permutation;
    }

    void Permutation(string str,int nSize, int n)
    {
        if (n == str.size())
        {
            permutationSet.insert(str);
        }

        else
        {
            Permutation(str, nSize, n + 1);
            for (int i = n+1; i < str.size(); ++i)
            {
                if (str[n] != str[i])
                {
                    char tmp = str[n];
                    str[n] = str[i];
                    str[i] = tmp;

                    Permutation(str, nSize, n + 1);

                    tmp = str[n];
                    str[n] = str[i];
                    str[i] = tmp;
                }
            }
        }
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609385&siteId=291194637