I am facing following problem with recursion. It is simple backtracking to print all the permutation, but I want to stop it from the base condition. For example, 4 character string will show 4!=24 strings. But I want to show first 20 strings only. k is used for the purpose, k=20,for the example. Suppose, str="ABCD". I want to stop recursion after exactly 20 operations. How can I do this? I have tried to solve it in this way.
void permutation(string str,int l,int r,int k)
{
k--;
if(l==r||k==0) {
cout<<str<<endl;
return;
}
else{
for(int i=l;i<r;i )
{
swap(str[l],str[i]);
permutation(str,l 1,r,k);
swap(str[l],str[i]);
}
}
}
CodePudding user response:
If you want to use the unfortunately named k
as a counter like that, it will count recursion levels, not results. If you want to count results, you need to store the counter outside of your function, either as a static or as a reference you pass to your function, and increment it every time you output a result.
CodePudding user response:
You have two solutions to count the number of times results are printed:
1- Defining k
as a global variable outside the function.
2- Defining k
as a static variable: static int k = 0;
.
Note that in both these solutions, k
should be eliminated from the parameter list of the function.
I would also suggest choosing meaningful names for your variables. This way, it will be easier to understand and follow the code both for you and someone else who is going to help.
Please remember to upvote the solution if it helped.