Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
这道题感觉多层循环暴力求解是行不通的,因为数字串的长度未知。那么如果我们每次按顺序选定一个数字代表的字母,然后只需要求剩下子串所有的组合可能,按这样的思路考虑,我觉得递归可行,于是我就尝试了以下。
以下是AC的代码
class Solution {
public:
vector<string> signs = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> recur_substr(char c, string s) {
vector<string> a;
int t = c-'0'-2;
if (s.size() == 0) {
for (int i = 0; i < signs[t].size(); i++) {
string temp;
temp += signs[t][i];
a.push_back(temp);
}
} else {
vector<string> latter;
if (s.size() == 1) {
latter = recur_substr(s[0], "");
} else {
latter = recur_substr(s[0], s.substr(1));
}
for (int i = 0; i < signs[t].size(); i++) {
for (int j = 0; j < latter.size(); j++) {
a.push_back(signs[t][i]+latter[j]);
}
}
}
return a;
}
vector<string> letterCombinations(string digits) {
vector<string> ans;
if (digits.empty()) {
return ans;
}
if (digits.size()==1) {
ans = recur_substr(digits[0], "");
} else {
ans = recur_substr(digits[0], digits.substr(1));
}
return ans;
}
};