問題
給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。
給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。
示例:
輸入:“23”
輸出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
說明:
儘管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。
思路
以上面示例爲例:
“2” 和 “3” 對應的是["a", "b", "c"]
和 ["d", "e", "f"]
之間所有的組合情況。
所產生的結果可以看作是一個樹的結構。
代碼
/**
* @param {string} digits
* @return {string[]}
*/
const PhoneChart = [
['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']
]
var letterCombinations = function(digits) {
const letters = digits.split('').map(index => PhoneChart[index - 2])
const digitLength = letters.length
if(digitLength <= 0) return []
let rs = letters[0]
for(let i = 1; i < digitLength; i++) {
rs = [].concat(...letters[i].map(addon => rs.map(pre => pre + addon)))
}
return rs
};
結果
Accepted
25/25 cases passed (56 ms)
Your runtime beats 95.34 % of javascript submissions
Your memory usage beats 17.68 % of javascript submissions (33.8 MB)
思考
用了很多的內存,emmmm…