LeetCode 17 Letter Combinations of a Phone Number

来源:互联网 发布:乡镇网络舆情预警机制 编辑:程序博客网 时间:2024/04/30 03:13

原题:(频率3)

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.





题意:求输入的数字对应的英文的所有组合




代码和思路

//回溯法class Solution {    //对应0-9的字母    private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };        public List<String> letterCombinations(String digits) {                List<String> res = new LinkedList<>();        if(digits.length()==0 || digits == null) return res;        backtrack("",digits,0,res);        return res;    }        private void backtrack(String prefix,String digits,int i,List<String> res){        //i是代表digits的第几个数字,大于等于最后一个数字的长度时结束        if(i>=digits.length()){            res.add(prefix);            return;        }        //第i个数字所对应的所有字母        String letters = KEYS[(digits.charAt(i)-'0')];        //每一个字母进行下一次迭代,直到满足 i>=digits.length()        for(int j = 0; j < letters.length(); j++){            backtrack(prefix + letters.charAt(j), digits, i+1, res);        }    }}