Are there any better methods to do permutation of string?

前端 未结 20 1590
醉话见心
醉话见心 2020-11-27 11:15
void permute(string elems, int mid, int end)
{
    static int count;
    if (mid == end) {
        cout << ++count << \" : \" << elems << end         


        
20条回答
  •  暖寄归人
    2020-11-27 11:47

    Here yet another recursive function for string permutations:

    void permute(string prefix, string suffix, vector &res) {
        if (suffix.size() < 1) {
            res.push_back(prefix);
            return;
        }
        for (size_t i = 0; i < suffix.size(); i++) {
            permute(prefix + suffix[i], suffix.substr(0,i) + suffix.substr(i + 1), res);
        }
    }
    
    
    int main(){
        string str = "123";
        vector res;
        permute("", str, res);
    }
    

    The function collects all permutations in vector res. The idea can be generalized for different type of containers using templates and iterators:

    template 
    void permute(typename Cont1_t prefix,
        typename Cont1_t::iterator beg, typename Cont1_t::iterator end,
        Cont2_t &result)
    {
        if (beg == end) {
            result.insert(result.end(), prefix);
            return;
        }
        for (auto it = beg; it != end; ++it) {
            prefix.insert(prefix.end(), *it);
            Cont1_t tmp;
            for (auto i = beg; i != end; ++i)
                if (i != it)
                    tmp.insert(tmp.end(), *i);
    
            permute(prefix, tmp.begin(), tmp.end(), result);
            prefix.erase(std::prev(prefix.end()));
        }
    }
    
    int main()
    {
        string str = "123";
        vector rStr;
        permute>("", str.begin(), str.end(), rStr);
    
        vectorvint = { 1,2,3 };
        vector> rInt;
        permute, vector>>({}, vint.begin(), vint.end(), rInt);
    
        list ll = { 1,2,3 };
        vector> vlist;
        permute, vector>>({}, ll.begin(), ll.end(), vlist);
    }
    

    This may be an interesting programming exercise, but in production code you should use a non recusrive version of permutation , like next_permutation.

提交回复
热议问题