Letter Combinations of a Phone Number
Backtracking
Medium
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:
Input:
"23"
Output:
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Analysis
The phone digits to letters mapping:
String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }Solution
Recursive
利用递归,每次递归选择当前数字对应字符,然后将index+1,用下一个数字进入下一层递归;递归返回的条件是String path达到digits的长度,代表了一个组合的生成结束了,放入结果中即可。
Time complexity : O(3^N × 4^M ) where N is the number of digits in the input that maps to 3 letters (e.g. 2, 3, 4, 5, 6, 8) and M is the number of digits in the input that maps to 4 letters (e.g. 7, 9), and N+M is the total number digits in the input.
Space complexity : O(3^N × 4^M ) since one has to keep 3^N times 4^M solutions.
https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/
Queue, BFS
Last updated
Was this helpful?