이 문제에서 문자열 str이 주어지고 모든 문자 조합을 사전순으로 인쇄해야 합니다.
문제를 더 잘 이해하기 위해 예를 들어 보겠습니다 -
Input: str = ‘XYZ’ Output : X XY XYZ XZ XZY Y YX YXZ YZ YZX Z ZX ZXY ZY ZYX
이 문제를 해결하기 위해 문자열의 모든 문자 조합을 인쇄합니다. 이를 위해 문자열의 문자를 저장할 맵 데이터 구조가 필요합니다. 구현을 위해 모든 조합을 추적하기 위해 역추적을 사용해야 합니다.
예시
#include <bits/stdc++.h>
using namespace std;
void printResult(char* result, int len);
void findstringCombination(char result[], char str[], int count[],int level, int
size, int length) ;
void printCharCombination(string str);
int main(){
string str = "ABC";
cout<<"The combination of characters of the string :\n";
printCharCombination(str);
return 0;
}
void findstringCombination(char result[], char str[], int count[],int level, int size, int length){
if (level == size)
return;
for (int i = 0; i < length; i++) {
if (count[i] == 0)
continue;
count[i]--;
result[level] = str[i];
printResult(result, level);
findstringCombination(result, str, count, level + 1, size, length);
count[i]++;
}
}
void printCharCombination(string str){
map<char, int> mp;
for (int i = 0; i < str.size(); i++) {
if (mp.find(str[i]) != mp.end())
mp[str[i]] = mp[str[i]] + 1;
else
mp[str[i]] = 1;
}
char* input = new char[mp.size()];
int* count = new int[mp.size()];
char* result = new char[str.size()];
map<char, int>::iterator it = mp.begin();
int i = 0;
for (it; it != mp.end(); it++) {
input[i] = it->first;
count[i] = it->second;
i++;
}
int length = mp.size();
int size = str.size();
findstringCombination(result, input, count, 0, size, length);
}
void printResult(char* result, int len){
for (int i = 0; i <= len; i++)
cout<<result[i];
cout<<endl;
} 출력
문자열의 문자 조합 -
A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA