[Problem] Permutations with repeated characters

Revision en2, by 1507002, 2020-06-20 22:31:34

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

Tags #permutation, #combinatorics, #number_theory, #next permutation

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English 1507002 2020-06-20 22:32:21 12
en2 English 1507002 2020-06-20 22:31:34 87
en1 English 1507002 2020-06-20 22:29:52 894 Initial revision (published)