LeetCode 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.

LeetCode 17.Letter Combinations of a Phone Number_第1张图片
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.

题意:将数字的字符串,转换成所有可能的字符串,放到一个list中。

分析:此题已经有一点难度了,因为我们不确定数字的字符串有多长,所以我们不可以单纯的利用for循环来做这道题来,我们需要用到递归算法来做这道题。

java代码:

class Solution {
    public List letterCombinations(String digits) {
    HashMap map = new HashMap();
    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'});
 
    List result = new ArrayList();
    if(digits.equals(""))
        return result;
 
    helper(result, new StringBuilder(), digits, 0, map);
 
    return result;
 
}
 
public void helper(List result, StringBuilder sb, String digits, int index, HashMap map){
    if(index>=digits.length()){
        result.add(sb.toString());
        return;
    }
 
    char c = digits.charAt(index);
    char[] arr = map.get(c);
 
    for(int i=0; i

你可能感兴趣的:(LeetCode 17.Letter Combinations of a Phone Number)