The output for "AABC" should be like this: AABC, AACB, ABAC, ABCA, ACAB, ACBA, BAAC, BACA, BCAA, CAAB, CABA, CBAA.
But the output of my code doesn't match with above. Can anyone find my where is the problem?
My Code
#include <bits/stdc++.h>
using namespace std;
void permute(char str[], int count[], char result[], int level){
if(level == strlen(result)){
cout << result << "\n";
return;
}
for(int i=0; i<strlen(str); i++){
if(count[i] == 0) continue;
result[level] = str[i];
count[i]--;
permute(str, count, result, level+1);
count[i]++;
}
}
int main(){
char str[] = "AABC";
int n = strlen(str);
int cnt[n] = {0};
for(int i=0; i<n; i++){
int index = (str[i] - 'A');
cnt[index]++;
}
char result[n];
permute(str, cnt, result, 0);
return 0;
}
The output of my code: AAA, AAB, AAA, AAB, ABA, ABA, AAA, AAB, ABA, BAA, BAA, BAA,








So, you can use std::next_permutation()
Use strings instead of char arrays and the problem will solve itself. strlen of result (first line of permute method) only works correctly if the position after the end of the array is the first 0 in memory, which is unlikely to be the case.
In particular, you should be looking at the length of the string str, not of the length of result. Either way if you just use vectors and strings instead it will all work better.
solved