[leedcode 17] Letter Combinations of a Phone Number

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);
        }
        
        
    }
}

 

你可能感兴趣的:(number)