Cho chuỗi độ dài <10, in tất cả viết tắt alphanumeric: ký tự xen kẽ số chỉ số ký tự bỏ qua. Không hai số liền nhau.
Ví dụ: "HELLO" -> "HELLO", "HELL1", "HEL1O", "HEL2", ...
Thuật toán đệ quy
printAbbreviation(s, index, max, str)
NẾU index==max: IN str, TRẢ VỀ
THÊM s[index] VÀO str; GỌI ĐỆ QUY(index+1)
XÓA KÝ TỬ CUỐI str
count = 1
NẾU str KHÔNG RỖNG VÀ KÝ TỬ CUỐI LÀ SỐ
count += GIÁ TRỊ SỐ ĐÓ; XÓA KÝ TỬ CUỐI
THÊM count VÀO str; GỌI ĐỆ QUY(index+1)
Chương trình C++ ví dụ
#include <iostream>
using namespace std;
void printAbbreviation(const string& s, int index, int max_index, string str) {
if (index == max_index) { cout << str << endl; return; }
str.push_back(s[index]);
printAbbreviation(s, index+1, max_index, str);
str.pop_back();
int count = 1;
if (!str.empty() && isdigit(str.back())) {
count += str.back() - '0';
str.pop_back();
}
str.push_back('0' + count);
printAbbreviation(s, index+1, max_index, str);
}
void printCombination(string str) {
if (!str.length()) return;
printAbbreviation(str, 0, str.length(), "");
}
int main() { printCombination("HELLO"); }
Kết quả
HELLO HELL1 HEL1O HEL2 HE1LO HE1L1 HE2O HE3 H1LLO H1LL1 H1L1O H1L2 H2LO H2L1 H3O H4 1ELLO 1ELL1 1EL1O 1EL2 1E1LO 1E1L1 1E2O 1E3 2LLO 2LL1 2L1O 2L2 3LO 3L1 4O 5