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.
An example of a duplicate would be "12"=="21" or "123"=="213".
Assume a character will not be used more than once. Also I don't think recursion is mandatory.
There's a php answer here.(Get all possible combinations without duplicates).
I have thought about some form of results tree but unsure how to implement with recursion.
My answer that includes duplicates is below:
#include <string>
#include <iostream>
using namespace std;
void get( string str, string res ) {
cout << res << endl;
for( int i = 0; i < str.length(); i++ )
get( string(str).erase(i,1), res + str[i] );
}
int main( int argc, char **argv) {
string str = "123";
get( str, "" );
return 0;
}
This was an interview question and the no duplicates thing threw me. Thanks in advance for any help.