题目
 
电话号码的字母组合
 
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
 
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
 
 
示例:
 
输入:“23” 输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
 
答案
 
class Solution {
    public List
<String> letterCombinations(String digits
) {
        List
<String> ans
=new ArrayList<String>();
        if (digits
.length()==0){
            return ans
;
        }
        
        Map
<Character,String> phoneMap 
= new HashMap();
        phoneMap
.put('2',"abc");
        phoneMap
.put('3',"def");
        phoneMap
.put('4',"ghi");
        phoneMap
.put('5',"jkl");
        phoneMap
.put('6',"mno");
        phoneMap
.put('7',"pqrs");
        phoneMap
.put('8',"tuv");
        phoneMap
.put('9',"wxyz");
        backtrack(phoneMap
,digits
,0,ans
,new StringBuffer());
        return ans
;
    }
    public void backtrack(Map
<Character,String> phoneMap
,String digits
,int index
,List
<String> ans
,StringBuffer sb
){
        
        
        if (sb
.length() == digits
.length()){
            ans
.add(sb
.toString());
        }else {
            
            
            String s
=phoneMap
.get(digits
.charAt(index
));
            
            for (int i
=0;i
<s
.length();i
++){
                
                sb
.append(s
.charAt(i
));
                
                backtrack(phoneMap
,digits
,index
+1,ans
,sb
);
                
                
                sb
.deleteCharAt(sb
.length()-1);
            }
        }
    }
}