题目:
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.
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.
题解:
这道题也是来算一种combination的题,跟 Combinations 和 Word Break II 都比较类似(其实和leetcode里面很多题都相似)。
代码如下:
1
public ArrayList<String> letterCombinations(String digits) {
2 ArrayList<String> result=
new ArrayList<String>();
3
if (digits==
null)
4
return result;
5
6 String[] keyboard={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
7 StringBuilder current=
new StringBuilder();
8
9
int index=0;
10 buildResult(digits, index, current, keyboard, result);
11
return result;
12 }
13
14
private
void buildResult(String digits,
int index, StringBuilder current, String[] keyboard, ArrayList<String> result){
15
if (index==digits.length()){
16 result.add(current.toString());
17
return;
18 }
19
20
int num=digits.charAt(index)-'0';
//
get integer number
21
for (
int i=0; i<keyboard[num].length(); i++){
22 current.append(keyboard[num].charAt(i));
23 buildResult(digits, index+1, current, keyboard, result);
24 current.deleteCharAt(current.length()-1);
25 }
26 }
Refrence:http://rleetcode.blogspot.com/2014/02/letter-combinations-of-phone-number-java.html