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.
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;
}