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) { String[] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; List<String> res = new ArrayList<String>(); rec(res, new StringBuilder(), digits, map, 0); return res; } private void rec(List<String> res, StringBuilder sb, String digits, String[] map, int level){ if(level==digits.length() ){ res.add(sb.toString()); return; } String s = map[digits.charAt(level)-'2']; for(int i=0; i<s.length(); i++) { sb.append(s.charAt(i)); rec(res, sb, digits, map, level+1); sb.deleteCharAt(sb.length()-1); } } }