320. Generalized Abbreviation
Write a function to generate the generalized abbreviations of a word.
Note: The order of the output does not matter.
Example:
Input: "word"
Output:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]// Backtracking
vector<string> generateAbbreviations(string word) { // time: O(2^n); space: O(2^n)
vector<string> res;
string cur;
helper(word, res, cur, 0, 0);
return res;
}
void helper(string& word, vector<string>& res, string cur, int idx, int count) {
if (idx >= word.size()) {
if (count) cur += to_string(count);
res.push_back(cur);
} else {
helper(word, res, cur, idx + 1, count + 1); // abbreviate the current char
if (count) cur += to_string(count);
helper(word, res, cur + word[idx], idx + 1, 0); // use the current char after adding the count number to cur
}
}Last updated
Was this helpful?