Letter Combinations of a Phone Number
Given a string containing digits from
2-9
inclusive, 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. Note that 1 does not map to any letters.
Note: Although the above answer is in lexicographical order, your answer could be in any order you want.
Example 1
1 | Input: "23" |
解题思路
每个数字对应一系列字母,从前往后遍历数字,将数字替换为字母。因为每个数字替换有多种选择,很容易想到回溯法。每当树的一层被完全展开(即完成所有替换选择),便回到上一层做下一个选择并展开。
复杂度分析
- 时间复杂度:$O(m^n)$,
m
为每个数字对应的最大字母数量。 - 空间复杂度:$O(n)$,除去返回结果,只用了一个额外的字符串。
代码
1 | class Solution { |