美文网首页
leetcode #17 Letter Combinations

leetcode #17 Letter Combinations

作者: huntriver | 来源:发表于2017-09-16 13:59 被阅读0次

    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;
    };
    

    相关文章

      网友评论

          本文标题:leetcode #17 Letter Combinations

          本文链接:https://www.haomeiwen.com/subject/cuwysxtx.html