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.

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<String> letterCombinations(String digits) {
    HashMap<Character, char[]> map = new HashMap<Character, 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'});
 
    List<String> result = new ArrayList<String>();
    if(digits.equals(""))
        return result;
 
    helper(result, new StringBuilder(), digits, 0, map);
 
    return result;
 
}
 
public void helper(List<String> result, StringBuilder sb, String digits, int index, HashMap<Character, char[]> 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<arr.length; i++){
        sb.append(arr[i]);
        helper(result, sb, digits, index+1, map);
        sb.deleteCharAt(sb.length()-1);
    }
}
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容