Letter Combinations of a Phone Number

拼搏现实的明天。 2021-12-17 10:41 308阅读 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.

200px-Telephone-keypad2.svg.png

  1. Input:Digit string "23"
  2. Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

这题是组合题,思路很简答,需要同时掌握迭代和递归两种方法。递归都很清楚,思路为dfs + backtracking,迭代版的思路为在之前生成的中间结果上再加一位构成现在的结果。

迭代版思路如下:

  1. def letterCombinations(self, digits):
  2. """
  3. :type digits: str
  4. :rtype: List[str]
  5. """
  6. hash = {
  7. '2':'abc', '3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
  8. #iterative method
  9. if not digits:
  10. return []
  11. res = [[]]
  12. for i in digits:
  13. tmp = []
  14. for j in hash[i]:
  15. for num in res:
  16. tmp.append(num + [j]) #取之前结果加1
  17. res = tmp + []
  18. return map(lambda x: ''.join(x),res)

递归版本:

  1. class Solution(object):
  2. def letterCombinations(self, digits):
  3. """
  4. :type digits: str
  5. :rtype: List[str]
  6. """
  7. hash = {
  8. '2':'abc', '3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
  9. comb = []
  10. for i in digits:
  11. if i in hash:
  12. comb.append(hash[i])
  13. if not comb:
  14. return []
  15. n = len(comb)
  16. res = []
  17. self.dfs(res, comb, [], 0, n)
  18. return res
  19. def dfs(self, res, comb, cur, index, n):
  20. if index == n:
  21. res.append(''.join(cur))
  22. return
  23. for j in xrange(len(comb[index])):
  24. cur.append(comb[index][j])
  25. self.dfs(res, comb, cur, index+1, n)
  26. cur.pop()

总结而言python处理这种题不是很高效,主要在于string类型对象不可以修改。

转载于:https://www.cnblogs.com/sherylwang/p/5764002.html

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读