链接:http://www.lintcode.com/zh-cn/problem/generalized-abbreviation/
Write a function to generate the generalized abbreviations of a word.
样例
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"]
思路:
要枚举,要么递归要么迭代,递归算法思路:每个字母都只有两种情况,保留或者缩写隐藏。用一个数记录缩写的字母数。
class Solution {
public:
/**
* @param word: the given word
* @return: the generalized abbreviations of a word
*/
vector<string> generateAbbreviations(string &word) {
// Write your code here
vector<string> res;
backtrack(res,"",word,0,0);
return res;
}
void backtrack(vector<string>& res,string str,string word,int start,int count)
{
if(start==word.length())
{
if(count>0)
{
str=str+to_string(count);
}
res.push_back(str);
}
else
{
backtrack(res,str,word,start+1,count+1);
backtrack(res,str+(count>0?to_string(count):"")+word[start],word,start+1,0);
}
}
};