Letter Combinations of a Phone Number
Given a string containing digits from2-9inclusive, 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.
Example
Note1
类似笛卡尔积,需要建立数字和字母的映射
private final String[] mappings = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
index控制第几个数字,终止条件即index遍历完号码,同时dfs遍历每个映射内部的字母
Code1
Note2
BFS方法,队列里增加的是长度逐渐增加的结果,其长度就是BFS的层数
第一层 a b c
第二层 对之前每个元素加上 d e f
当字符串长度和数字长度一致时,就加入结果
Code2
Last updated