Generate list of all possible permutations of a string

后端 未结 30 2552
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  北海茫月
    2020-11-22 15:18

    There are a lot of good answers here. I also suggest a very simple recursive solution in C++.

    #include 
    #include 
    
    template
    void permutations(std::string s, Consume consume, std::size_t start = 0) {
        if (start == s.length()) consume(s);
        for (std::size_t i = start; i < s.length(); i++) {
            std::swap(s[start], s[i]);
            permutations(s, consume, start + 1);
        }
    }
    
    int main(void) {
        std::string s = "abcd";
        permutations(s, [](std::string s) {
            std::cout << s << std::endl;
        });
    }
    

    Note: strings with repeated characters will not produce unique permutations.

提交回复
热议问题