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.

題意:將數(shù)字的字符串,轉(zhuǎn)換成所有可能的字符串,放到一個(gè)list中。

分析:此題已經(jīng)有一點(diǎn)難度了,因?yàn)槲覀儾淮_定數(shù)字的字符串有多長(zhǎng),所以我們不可以單純的利用for循環(huán)來(lái)做這道題來(lái),我們需要用到遞歸算法來(lái)做這道題。

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);
    }
}
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容