17. Letter Combinations of a Phone Number
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
js
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
var table = [
[],
[],
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r', 's'],
['t', 'u', 'v'],
['w', 'x', 'y', 'z']
]
digits = digits.split('')
var result = digits.reduce((ret, num) => {
return combine(ret, table[num])
}, [])
return result
function combine(arr1, arr2) {
if (!arr1.length) {
return arr2
}
if (!arr2.length) {
return arr1
}
var result = []
arr1.forEach(a => {
arr2.forEach(b => {
result.push(a + b)
})
})
return result
}
}
py
from functools import reduce
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
table = [
[],
[],
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r', 's'],
['t', 'u', 'v'],
['w', 'x', 'y', 'z']
]
letters = [table[int(num)] for num in list(digits)]
def combine(l1, l2):
if not l1:
return l2
if not l2:
return l1
result = []
for a in l1:
for b in l2:
result.append(a + b)
return result
return reduce(combine, letters, [])