[leedcode 17] 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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
public class Solution { public List<String> res; public StringBuilder seq; public List<String> letterCombinations(String digits) { //本题类似于全排列的变形,全排列的每一位可选值需要根据传入的数字对应取出 //dfs思想。循环中叠加递归,递归函数需要一个参数level,表示递归的位数 res=new ArrayList<String>(); seq=new StringBuilder(); if(digits.length()==0) return res; String[] trans={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; getLetterCom(digits,0,trans); return res; } public void getLetterCom(String digits,int level,String trans[]){ if(level==digits.length()){ res.add(seq.toString()); return; } int n=digits.charAt(level)-'0'; String temp=trans[n]; for(int i=0;i<temp.length();i++){ seq.append(temp.charAt(i)); getLetterCom(digits,level+1,trans); seq.deleteCharAt(level); } } }