此道题目为经典的DFS题目,可以用DFS解决。很长时间没有写递归题目了,所以我的解法占用空间较大,比较高效的写法是只在栈中维护一个字符序列,而我的解法则是维护了3^N个字符序列,其中N为输入的digits的长度。我的代码如下:
string d2S[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> result, ret;
if (digits.size() == 0) {
return result;
}
int d = digits[0]-'0';
string s = d2S[d];
ret = letterCombinations(digits.substr(1)); // 这样写,是先递归子字符串。
for (int i=0; i<(int)s.size(); i++) {
string tmp = s.substr(i, 1);
if (ret.size() == 0) {
result.push_back(tmp);
} else {
for (int j=0; j<ret.size(); j++) {
result.push_back(tmp + ret[j]);
}
}
}
if (s.size() == 0) {
return ret;
} else {
return result;
}
}
更为高效的写法如下:
string d2S[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void generator(vector<string>& result, string& seq, string& digits, int deep) { // <span style="color:#ff0000;">seq为维护的字符序列,deep标示已经运行到了digits的第几位, result、seq以及digits都为引用形式</span>
<span style="color:#ff0000;"> </span> if (digits.size() == deep) {
result.push_back(seq);
return;
}
int index = digits[deep] - '0';
string letters = d2S[index];
if (letters.size() == 0) {
generator(result, seq, digits, deep+1);
}
for (int i=0; i<letters.size(); i++) { // <span style="color:#ff0000;">先对前面的字符进行运行,后递归子串
</span> seq.push_back(letters[i]);
generator(result, seq, digits, deep+1);
seq.pop_back();
}
}
vector<string> letterCombinations(string digits) {
vector<string> result;
string seq;
if (digits.size() == 0) {
return result;
}
generator(result, seq, digits, 0);
return result;
}