LeetCode 電話號碼的字母組合_17

 題目:

給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。

給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。

輸入:"23"
輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:DFS。 

代碼:

import java.util.*;

//DFS
public class 電話號碼的字母組合_17 {
    public List<String> letterCombinations(String digits) {
        List<String> res= new ArrayList<String>();
        if(digits.length()==0||digits==null) return res;
        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'});
        helper("",0,res,map,digits);
        return res;
    }

    public void helper(String s, int count, List<String> res, HashMap<Character,char[]> map, String digits) {
        if(count==digits.length())  res.add(s);
        else{
            char c=digits.charAt(count);
            if(map.containsKey(c))
            {
                for(char ch:map.get(c))
                {
                    /*
                        這裏寫第二個參數的時候,我本來寫的是count++,會報錯。後來試了count+1。
                        因爲在讀第i個字母的時候,要進到第i+1個字母裏去..不斷搜索下去,
                        如果寫count++,當搜索結束回到第i層時,count就不是原來的i了。

                        寫了count+1,繼續往下搜索,搜完後再次回來還是原來count的值。
                     */
                    helper(s+ch ,count+1,res,map,digits);
                }
            }else{

            }
        }

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章