leetcode #17 Letter Combinations

2017-09-16  本文已影响0人  huntriver

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;
};
上一篇下一篇

猜你喜欢

热点阅读