Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = "" Output: []
Example 3:
Input: digits = "2" Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i]
is a digit in the range['2', '9']
.
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
n = len(digits)
if n == 0:
return []
chars = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
strs = [chars[int(d) - 2] for d in digits]
res = []
for s in strs:
if not res:
res = list(s)
else:
cache = []
for item in res:
for letter in s:
cache.append(item + letter)
res = cache
return res
class Solution {
public List<String> letterCombinations(String digits) {
int n;
if ((n = digits.length()) == 0) return Collections.emptyList();
List<String> chars = Arrays.asList("abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz");
List<String> strs = new ArrayList<>();
for (char c : digits.toCharArray()) {
strs.add(chars.get(c - '0' - 2));
}
List<String> res = new ArrayList<>();
for (String str : strs) {
if (res.size() == 0) {
for (char c : str.toCharArray()) {
res.add(String.valueOf(c));
}
} else {
List<String> cache = new ArrayList<>();
for (String item : res) {
for (char c : str.toCharArray()) {
cache.add(item + String.valueOf(c));
}
}
res = cache;
}
}
return res;
}
}