Get all combinations without duplicates

前端 未结 2 803
[愿得一人]
[愿得一人] 2021-01-26 23:40

Give all possible combinations of a string without duplicates in c++. Example input: \"123\" and output combinations will be:

 1,12,123,13,2,23,3.
2条回答
  •  别那么骄傲
    2021-01-27 00:22

    Thought I'd add an answer from @Caninonos in the comments. I just simplified it slightly removing templates etc. This is a recursive solution.

    #include 
    #include 
    using namespace std;
    
    void get_substrings_aux(vector& subs, string str ,unsigned int cnt) {
    
        if(cnt == str.size())
        return;
    
        int n = subs.size();
        char c = str[cnt];
        for(int i = 0 ; i < n ; ++i) {
            subs.push_back(subs[i] + c);
            cout << subs[i] + c << endl;
        }
        get_substrings_aux(subs, str, ++cnt);
    }
    
    vector get_substrings(const string& str) {
        vector subs(1);
        int cnt=0;
        get_substrings_aux(subs, str, cnt);
        subs.erase(subs.begin());
        return subs;
    }
    
    int main() {
        string str("1234");
        vector subs = get_substrings(str);
        return 0;
    }
    

提交回复
热议问题