题目:
Write a function to generate the generalized abbreviations of a word.
Example:
Given word = "word"
, return the following list (order does not matter):
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
思路:
凡是返回解集合的题目大多数都可以用回溯法求解,本题目也不例外。对于单词word的第i个字符word[i],我们有两种处理方法:1)将word[i]转化为数字缩写;2)保留word[i]。这两种情况构成了DFS的两个搜索分支。当然在返回结果的时候,别忘了在num不为0的情况下,将其加入缩写结果的尾部。
代码:
class Solution {
public:
vector<string> generateAbbreviations(string word) {
vector<string> ret;
DFS(word, 0, ret, "", 0);
return ret;
}
private:
void DFS(string& word, int pos, vector<string>& ret, string line, int num) {
if(pos == word.length()) {
if(num != 0) {
line += to_string(num);
}
ret.push_back(line);
return;
}
DFS(word, pos + 1, ret, line, num + 1); // abbreviate word[pos]
DFS(word, pos + 1, ret, line + (num == 0 ? "" : to_string(num)) + word[pos], 0); // keep word[pos]
}
};