Hey , i was implementing next_permutation using recursion in c++. But i am getting wrong answer on 7/10 of test cases.
Heres the question-
Given a string containing duplicates, print all its distinct permutations such that there are no duplicate permutations and all permutations are printed in a lexicographic order.
NOTE: DO NOT USE MAP OR SET.
Input Format:
The first and only line of the test case contains the input string.
Constraints:
Length of the string <= 8
Output Format
Print all the distinct permutations in a lexicographic order such that each permutation is in a new line. Note that there should not be any duplicate permutations.
Sample Input
ABA
Sample Output
AAB ABA BAA
My solution -
#include<bits/stdc++.h>
using namespace std;
//checking is current element matches with any element then it will produce redundant results
bool checkif(string &in,int i,int j){
for(int k=i;k<j;k++){
if(in[k] == in[j])
return 0;
}
return 1;
}
void distinctPermutations(string &in,int i){
//Base case
if(in[i]==NULL){
cout<<in<<endl;
return;
}
//Recursive case
bool flag=0;
for(int j=i;in[j]!=NULL;j++){
bool check = checkif(in,i,j);
if(check) {
swap(in[j],in[i]);
distinctPermutations(in,i+1);
swap(in[j],in[i]);
}
}
}
int main() {
// your code goes here
string in;
cin>>in;
sort(in.begin(),in.end());
distinctPermutations(in,0);
return 0;
}