Algorithm to generate all combinations of a string

前端 未结 10 1936
日久生厌
日久生厌 2021-02-01 22:47

I found a link online that shows an algorithm to generate all combinations of a string: http://www.mytechinterviews.com/combinations-of-a-string

Algorithm is copied belo

10条回答
  •  醉话见心
    2021-02-01 23:15

    Here is C++ code without the tricky backtracking step in OP's question.

    #include 
    #include 
    using namespace std;
    static const string in("abc");
    void combine(int i, string out)
    {
        if (i==in.size()) {
            cout << out << endl;
            return;
        }
        combine(i+1, out);
        combine(i+1, out+in[i]);
    }
    
    int main()
    {
        combine(0, "");
        return 0;
    }
    

    I hope this better captures the spirit of combinations.

提交回复
热议问题