17. Letter Combinations of a Phone Number
- Total Accepted: 110517
- Total Submissions: 349102
- Difficulty: Medium
- Contributors: Admin
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.
代码如下
public class Solution {
public List<String> letterCombinations(String digits) {
ArrayList<String> result = new ArrayList<String>();
if (digits.length()==0) {
return new ArrayList<String>();
}
String map[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
dfs(result, 0, map, digits, new StringBuffer());
return result;
}
private void dfs(ArrayList<String> ret, int index, String[] str, String digits, StringBuffer sb) {
if (index == digits.length()) {
ret.add(sb.toString());
return;
}
String s = str[digits.charAt(index)-'0'];
for (int i = 0; i < s.length(); i++) {
sb = sb.append(s.charAt(i));
dfs(ret, index+1, str, digits, sb);
sb.deleteCharAt(sb.length()-1);
}
}
}