返回

穷举法——解锁电话号码的字母组合:算法300题之17

前端

欢迎来到算法之旅的第17站!本次,我们将踏上一个有趣的探秘之旅,探索如何将枯燥的电话号码转换成妙趣横生的字母组合。

一、题目

给定一个包含数字的字符串,返回所有可能的字母组合。

例如,给定数字 "23",返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]。

二、解法总览(思维导图)

[思维导图链接]

三、全部解法

1. 方案1

穷举法是一种简单直接的解决办法。它通过遍历所有可能的组合来生成答案。

1) 代码:

def letterCombinations(digits):
  if not digits:
    return []

  mapping = {
    "2": "abc",
    "3": "def",
    "4": "ghi",
    "5": "jkl",
    "6": "mno",
    "7": "pqrs",
    "8": "tuv",
    "9": "wxyz"
  }

  result = []
  combinations = [""]

  for digit in digits:
    new_combinations = []
    for combination in combinations:
      for letter in mapping[digit]:
        new_combinations.append(combination + letter)
    combinations = new_combinations

  return combinations

2. 方案2

回溯法是一种更有效率的解法。它通过递归地探索所有可能的组合来生成答案。

1) 代码:

def letterCombinations(digits):
  if not digits:
    return []

  mapping = {
    "2": "abc",
    "3": "def",
    "4": "ghi",
    "5": "jkl",
    "6": "mno",
    "7": "pqrs",
    "8": "tuv",
    "9": "wxyz"
  }

  result = []
  combination = ""

  def backtrack(index):
    if index == len(digits):
      result.append(combination)
      return

    digit = digits[index]
    for letter in mapping[digit]:
      combination += letter
      backtrack(index + 1)
      combination = combination[:-1]

  backtrack(0)
  return result

四、总结

电话号码的字母组合问题是一个经典的算法难题。通过穷举法或回溯法,我们可以高效地生成所有可能的字母组合。掌握这些算法技巧将极大地提升你在算法竞赛中的竞争力。