17. Letter Combinations of a Phone Number

来源:互联网 发布:nginx 转发到其他ip 编辑:程序博客网 时间:2024/06/02 06:23

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.


Solution:

Tips:

recursion


Java Code :

public class Solution {    public List<String> letterCombinations(String digits) {        List<String> ls = new ArrayList<>();        char[] dc = digits.toCharArray();        for (int i = 0; i < dc.length; i++) {            if (!(dc[i] > '1' && dc[i] <= '9')) {                return ls;            }        }        Map<Integer, String> mcs = new HashMap<>();        mcs.put(2, "abc");        mcs.put(3, "def");        mcs.put(4, "ghi");        mcs.put(5, "jkl");        mcs.put(6, "mno");        mcs.put(7, "pqrs");        mcs.put(8, "tuv");        mcs.put(9, "wxyz");        String str = "";        List<String> result = new ArrayList<>();        letterCombinations(digits, str, 0, mcs, result);        return result;    }        public void letterCombinations(String digits, String str, int k, Map<Integer, String> mcs, List<String> result) {        if (k == digits.length()) {            if (str != "") {                result.add(str);            }            return;        }        for (int i = k; i < digits.length(); i++) {            String cs = mcs.get(digits.charAt(i) - '0');            for (int j = 0; j < cs.length(); j++) {                if (str.length() == i) {                    letterCombinations(digits, str + cs.charAt(j), i + 1, mcs, result);                }            }        }    }}


0 0
原创粉丝点击