# 【leetcode】 17. Letter Combinations of a Phone Number

xiaoxiao2021-02-28  12

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 List<String> letterCombinations(String digits) { List<String> list=new ArrayList<String>(); if(digits.length()==0) return list; String[] strs=new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; char[] cur=new char[digits.length()]; getCombination(digits,0,strs,list,cur); return list; } public void getCombination(String digits,int count,String[] strs,List<String> list,char[] cur){ if(count==digits.length()){ list.add(new String(cur)); return; }else{ String str=strs[digits.charAt(count)-'2']; for(int i=0;i<str.length();i++){ cur[count]=str.charAt(i); getCombination(digits,count+1,strs,list,cur); } } } 或者

public List<String> letterCombinations(String digits){ List<String> list=new ArrayList<String>(); if(digits.length()==0) return list; String[] strs=new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; StringBuilder sb=new StringBuilder(); getCombination(digits,0,strs,list,sb); return list; } public void getCombination(String digits,int count,String[] strs,List<String> list,StringBuilder cur){ if(count==digits.length()){ list.add(cur.toString()); return; }else{ String str=strs[digits.charAt(count)-'2']; for(int i=0;i<str.length();i++){ cur.append(str.charAt(i)); getCombination(digits,count+1,strs,list,cur); cur.deleteCharAt(cur.length()-1); } } }