leetcode #17 Letter Combinations of a Phone Number

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;
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容