LeetCode17, letter combination of phone number

Title description

Insert picture description here

The first method-recursive backtracking

Obviously, this is based on the enumeration of similar matrices. Establish a mapping and recurse. Each time the recursion is completed, the result is found once. The result is added to the corresponding list. It's easy to understand the code.

class Solution {
    
    
    public List<String> letterCombinations(String digits) {
    
    
        HashMap<Character,String[]> map = new HashMap<>();
        map.put('2',new String[]{
    
    "a","b","c"});
        map.put('3',new String[]{
    
    "d","e","f"});
        map.put('4',new String[]{
    
    "g","h","i"});
        map.put('5',new String[]{
    
    "j","k","l"});
        map.put('6',new String[]{
    
    "m","n","o"});
        map.put('7',new String[]{
    
    "p","q","r","s"});
        map.put('8',new String[]{
    
    "t","u","v"});
        map.put('9',new String[]{
    
    "w","x","y","z"});

        return getList(digits,map,"",0,new ArrayList<String>()); 
    }
    public List<String> getList(String digits,Map map,String s1,int index,List list){
    
    
        if(index>=digits.length()){
    
    
            return list;
        }
        String []nums = (String[])map.get(digits.charAt(index));
        for(int j=0;j<nums.length;j++){
    
    
            if(index==0){
    
    
                s1 = "";
            }
            String s = s1;//保存之前的值。
            s1+=nums[j];
            getList(digits,map,s1,index+1,list);
            if(index==digits.length()-1){
    
    
                list.add(s1);//添加完了一项。 
            }
            s1 = s;//之前的s1
           
        }
        return list;
    }
    
}

Insert picture description here

Looking at the beat rate of this submission, it's still a bit of a lot of approval. After all, it was the first time I made it.

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/108521261