1. 程式人生 > >17. Letter Combinations of a Phone Number (DFS, String)

17. Letter Combinations of a Phone Number (DFS, String)

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

思路:

還是通用DFS的套路,每一位依次在所有可能字元迴圈,然後遞迴到下一個號碼,直到位數已滿就回溯。

這道題的注意點是對字串和char的處理。

把鍵盤的對應存在陣列當中,去對應字串的時候有一操作很巧妙:

String cur = keys[digits.charAt(dig_pos)-'0'];//將char轉成數字

注意‘0’,‘1’都對應“”(空字串)。

private String[] keys = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<String>();
        if(digits==null || digits.equals(""))
            return res;
        doCombine("",res,0,digits);
        return res;
    }
    private void doCombine(String tmp, List<String> res, int dig_pos,String digits){
        if(tmp.length()==digits.length()){
            res.add(tmp);
            return;
        }
        String cur = keys[digits.charAt(dig_pos)-'0'];//將char轉成數字
        for(char c:cur.toCharArray()){
            String nstr = tmp + c;
            doCombine(nstr,res,dig_pos+1,digits);
        }
    }