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);
        }
    }
扫描二维码关注公众号,回复: 4891660 查看本文章

猜你喜欢

转载自blog.csdn.net/shulixu/article/details/86063118