LeetCode-电话号码的字母组合(No.17) 递归+hash

栏目: 数据库 · 发布时间: 5年前

内容简介:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。示例:

LeetCode 17. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。

注意 1 不对应任何字母。

LeetCode-电话号码的字母组合(No.17) 递归+hash

示例:

输入:"23"

输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

这道题的难点主要就是首先你能将输入的号码对应的结果映射出来,最后通过递归的形式两两组合得出结果

let letterCombinations = (digits) => {
  if (digits.length == 0) return [] //为空 情况
  let map = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
  let arr = digits.split('')
  let resarr = arr.map(item => map[item])
  if (resarr.length == 1) return resarr[0].split('')//仅输入一个 情况

  let compute = (arr) => {//组合传入数组的前两项  ['ab','cd','ewe']
    let temp = []         //['ac','ad','bc','bd']
    // 将前两项组合结果放入临时数组中  
    for (let i = 0; i < arr[0].length; i++) {
      for (let j = 0; j < arr[1].length; j++) {
        temp.push(`${arr[0][i]}${arr[1][j]}`)
      }
    }
    // [['ac','ad','bc','bd'],'ewe']
    arr.splice(0, 2, temp)//将原来的数组前两项结果用临时数组替换
    if (arr.length > 1) {
      compute(arr)
    }
    return arr[0]
  }
  return compute(resarr)
};

你也可以用这种哈希表的形式

let map = { //你也可以用这种哈希表的形式
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
  }

如果喜欢或者想要更多的信息, 可以戳这里 ,欢迎star


以上所述就是小编给大家介绍的《LeetCode-电话号码的字母组合(No.17) 递归+hash》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hacker's Delight

Hacker's Delight

Henry S. Warren Jr. / Addison-Wesley / 2002-7-27 / USD 59.99

A collection useful programming advice the author has collected over the years; small algorithms that make the programmer's task easier. * At long last, proven short-cuts to mastering difficult aspec......一起来看看 《Hacker's Delight》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具