Letter Combinations of a Phone Number
Solution 1
就是一个列举所有排列的问题。但是需要额外处理的地方就是输入序列的不定长度,因此无法直接使用循环实现。这里就需要使用典型的递归处理实现,就能够处理任意长度的输入序列了。
- 时间复杂度: O ( 3 i × 4 N − i ) O(3^i \times 4^{N - i}) O(3i×4N−i),其中 N N N为输入序列的长度, i i i为其中对应三个字母的数字个数
- 空间复杂度: O ( 3 i × 4 N − i ) O(3^i \times 4^{N - i}) O(3i×4N−i),其中 N N N为输入序列的长度, i i i为其中对应三个字母的数字个数
class Solution {
private:
vector<string> ans;
map<char, vector<char>> number2letter = {
{'2', {'a', 'b', 'c'}},
{'3', {'d', 'e', 'f'}},
{'4', {'g', 'h', 'i'}},
{'5', {'j', 'k', 'l'}},
{'6', {'m', 'n', 'o'}},
{'7', {'p', 'q', 'r', 's'}},
{'8', {'t', 'u', 'v'}},
{'9', {'w', 'x', 'y', 'z'}}
};
void getLetters(string digits, int pos, string temp) {
if (pos == digits.size()) {
ans.push_back(temp);
return;
}
vector<char> letters = number2letter[digits[pos]];
for (auto letter: letters) {
string tempNew = temp + letter;
getLetters(digits, pos + 1, tempNew);
}
}
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) {
return vector<string>();
}
getLetters(digits, 0, "");
return ans;
}
};
Solution 2
Solution 1对应的Python实现。
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
number2letter = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"]
}
ans = list()
def getLetters(tempStr:str, currentPos:int) -> None:
if currentPos >= len(digits):
ans.append(tempStr)
else:
for currentChar in number2letter[digits[currentPos]]:
tempStrNew = tempStr + currentChar
getLetters(tempStrNew, currentPos + 1)
if len(digits) == 0:
return ans
else:
getLetters("", 0)
return ans