Số hoán vị của chuỗi độ dài n là n!. Nếu có ký tự trùng, chia cho giai thừa của tần suất mỗi ký tự.
Công thức: n! / (freq[c1]! * freq[c2]! * ...)
Ví dụ code
#include <iostream>
#include <string>
using namespace std;
long fact(long n) {
return (n <= 1) ? 1 : n * fact(n-1);
}
int countPermutation(string str) {
int freq[26] = {0};
for (char c : str) freq[c - 'a']++;
int res = fact(str.size());
for (int f : freq) if (f > 1) res /= fact(f);
return res;
}
int main() {
string s; cout << "Nhập chuỗi: "; cin >> s;
cout << "Số hoán vị: " << countPermutation(s);
}Kết quả
Nhập chuỗi: abbc Số hoán vị: 12