[LeetCode] Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

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"].

思路:假如字符串长度已知,直接采用多重循环效率更高一些。不过这道题长度未知,使用递归,一层一层地递归下去,这种思路很重要,最后需要注意得是检查特殊情况null和""。
    public List<String> letterCombinations(String digits) { List<String> list=new ArrayList<String>(); if(digits==null || digits.length()==0) return list; digits=digits.replace("1",""); Map<Character, String> map=new HashMap<Character,String>(); 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"); map.put('0', " "); recurseStr(map , digits , 0 , list , ""); return list; } private void recurseStr(Map<Character,String> map,String digits,int depth,List<String> list,String re) { if(depth==digits.length()) { list.add(re); return; } String temp=map.get(digits.charAt(depth)); for(int i=0;i<temp.length();i++) { recurseStr(map,digits,depth+1, list, re+temp.charAt(i)); } }

 

你可能感兴趣的:(LeetCode)