I’ve been asked to write a permutation function that uses recursion. The only parameter of the function should be the string that I should find all the permutations of. The function should return a vector with all possible permutations. I know I can use next_permutation in STL Algorithms, but I’ve been asked not to.
I have the base case set up, and I know I need a for loop, but I’m not quite sure where to go from there. Can someone point me in the right direction?
vector <string> getPerm(string str)
{
vector<string> v;
if(w.length() <= 1)
{
v.push_back(str);
return v;
}
else
{
for(int i = 0; i < str.size(); i++)
{
//Some code
}
}
}
Any help would be appreciated.
Imagine you already have the result of the previous iteration of your function, with returns all the permutations of the first n-1 elements of your string.
Use this in the
part of your code.
Another tip: use the 0-length string as the stop-condition of your recursion. You can construct the 1-lenght permutations recursively 😉
Here is the entire solution: