Back --- the numeric keypad combinations

Numeric keyboard combination

17. Letter Combinations of a Phone Number (Medium)

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

1558943906219

Subject description:

  The figures given string, the composition of which corresponds to the combinations of letters Mobile phone keypad.

Analysis of ideas:

  This problem seeking string permutations, we use the idea to solve the back, each number corresponding to the first letter on the key as stored in the map, then traverse the numeric string, the idea of ​​using the back, a combination is obtained .

Code:

public List<String>letterCombinations(String digits){
    List<String>res=new ArrayList<>();
    if(digits==null||digits.length()==0)
        return res;
    HashMap<Character,char[]>map=new HashMap<>();
        map.put('0',new char[]{});
        map.put('1',new char[]{});
        map.put('2',new char[]{'a','b','c'});
        map.put('3',new char[]{'d','e','f'});
        map.put('4',new char[]{'g','h','i'});
        map.put('5',new char[]{'j','k','l'});
        map.put('6',new char[]{'m','n','o'});
        map.put('7',new char[]{'p','q','r','s'});
        map.put('8',new char[]{'t','u','v'});
        map.put('9',new char[]{'w','x','y','z'});
    StringBuilder str=new StringBuilder(); //将其中的一种结果保存
    findComb(digits,map,res,str);
    return res;
    }
public void findComb(String digits,HashMap<Character,char[]>map,List<String>res,StringBuilder str){
    if(str.length()==digits.length()){
        res.add(str.toString());
        return ;
    }
    for(char c:map.get(digits.charAt(str.length()))){
        str.append(c);//添加
        findComb(digits,map,res,str);
        str.deleteCharAt(str.length()-1)//每找出一个结果后,str的长度减一,添加下一种可能;
    }
}
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11111020.html