Problem
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
2:”abc”, 3-“def”, 4-“ghi”, 5-“jkl”, 6-“mno”, 7-“pqrs”, 8-“tuv”, 9-“wxyz”
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Examples:
Input:“23”
Output:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Solutions
- 递归,当后面的全部完成了排列之后,前面的加上就是全部的排列方式,这里要记录前缀,到最后没有数字的时候,就添加前缀并返回
C++ Codes
1 | class Solution { |
总结
- 递归要处理好边界条件,这里是当digits为空的时候,就返回
- 这里用了记录前缀的方式,感觉也可以使用前面的加上后缀的方式,返回的时候返回字符,应该也可以
- 这题让我想到了全排列的解法