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.
image.png
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
- 題目大意
對于老的手機,都是如上圖數字鍵盤,給定一串數字,輸出所有可能的字母組合。
其實就是暴力搜索,用遞歸實現會相對簡單。直接上代碼
/**
* @param {string} digits
* @return {string[]}
*/
const letters = {
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'],
};
var letterCombinations = function (digits) {
if (digits.length === 0) return []; // 遞歸停止條件
const c = digits[0];
const rest = digits.slice(1);
const restResult = letterCombinations(rest); //獲取剩余數字的可能組合
const result = [];
letters[c].forEach((letter) => {
if (restResult.length === 0) { //處理一位數字的特殊情況
result.push(letter);
}
restResult.forEach((str) => {
result.push(`${letter}${str}`);
});
});
return result;
};