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"].
递归的题老是做不好。拿到此题一直纠结于字母与数字的关系,可以再怎么纠结,也是得一个个遍历才可以。用DFS,注意if(ans.size()==0) ans.add("");
public class Solution { public ArrayList<String> letterCombinations(String digits) { ArrayList<String> ans = new ArrayList<String>(); ArrayList<Character> chars = new ArrayList<Character>(); HashMap<Character,String> map = new HashMap<Character,String>(); init(map); dfs(map,digits,0,chars,ans); if(ans.size()==0) ans.add(""); return ans; } private void dfs(HashMap<Character, String> map, String digits, int idx, ArrayList<Character> chars, ArrayList<String> arr){ if(idx >= digits.length()) return; char c = digits.charAt(idx); String s = map.get(c); for(int i = 0; i<s.length();i++){ if(idx == digits.length()-1){ chars.add(s.charAt(i)); StringBuilder sb = new StringBuilder(); for(char cc: chars){ sb.append(cc); } arr.add(sb.toString()); chars.remove(chars.size()-1); }else{ chars.add(s.charAt(i)); dfs(map,digits,idx+1,chars,arr); chars.remove(chars.size()-1); //char.remove(index) } } } private void init(HashMap<Character,String> map){ map.put('1', ""); map.put('2', "abc"); map.put('3', "def"); map.put('4', "ghi"); map.put('5', "jkl"); map.put('6', "mno"); map.put('7', "pqrs"); map.put('8', "tuv"); map.put('9', "wxyz"); } }