题目要求
1 2 3
| 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.
|
1 2 3 4 5
| Input:Digit string "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.
|
也就是说,将数字对应的字母的排列组合的的所有可能结果都枚举出来,顺序不唯一。
leetcode给这道题目加了一个标签很有意思,叫做Backtracking。点进去之后又很多类似的题目。这种类型的题目一般需要求出上一种情况的前提下才可以得知下一种情况。比如我必须先得知按下“2”后所有字母的可能值,才能在计算出“22”对应的可能值
思路一:递归
当我们无法直接得出结果的时候,我们可以借助递归让计算机帮我们考虑每一种情况并逐级得出当前的结果。在本思路中,我用了String数组来表示每一个按键对应的字母,其中数组的下标代表按键值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| String[] letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<String>(); for(int i = 0 ; i<digits.length() ; i++){ result = letterCombinations(digits.charAt(i), result); } return result; }
public List<String> letterCombinations(char digit, List<String> currentList){ int number = digit - '0'; String letter = letters[number]; if(letter.length()==0){ return currentList; } if(currentList.size() == 0){ for(int i = 0 ; i<letter.length() ; i++){ currentList.add(letter.charAt(i)+""); } return currentList; } List<String> result = new ArrayList<String>(); for(int i = 0 ; i<letter.length() ; i++){ for(int j = 0 ; j<currentList.size() ; j++){ StringBuilder temp = new StringBuilder(letter.charAt(i)+""); temp.insert(0, currentList.get(j)); result.add(temp.toString()); } } return result; }
|
思路二:队列(通过linkedlist实现)
从队列头获得上一种情况的结果,经过处理后添加到队列尾。这一种数据结构通过linkedList来实现。相比于上一种思路中ArrayList,linkedList内存占用更小,而且更加灵活。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| String[] letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations2(String digits) { LinkedList<String> l = new LinkedList<String>(); if(digits.length()==0){ return l; } l.add(""); int empty = 0; for(int i = 0 ; i < digits.length() ; i++){ int number = digits.charAt(i) - '0';
String letter = letters[number]; if(letter.length() == 0){ empty++; continue; } while(l.peek().length() + empty == i){ String peek = l.removeFirst(); for(int j = 0 ; j<letter.length() ; j++){ l.add(peek+letter.charAt(j)); } } } return l; }
|