Letter Combinations of a Phone Number

来源:互联网 发布:房屋平面图软件 编辑:程序博客网 时间:2024/04/28 07:29

Q:

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:

DFS. Need to remove the last added letter when we find a combination.

public class Solution {    static HashMap<Character, String> map = new HashMap<Character, String>();        static {            map.put('2', "abc");            map.put('3', "def");            map.put('4', "ghi");            map.put('5', "jkl");            map.put('6', "mno");            map.put('7', "pqrs");            map.put('8', "tuv");            map.put('9', "wxyz");        }    public List<String> letterCombinations(String digits) {        List<String> combines = new ArrayList<String>();        if (digits == null)            return combines;        char[] charDigits = digits.toCharArray();        String output = "";        generate(charDigits, 0, output, combines);        return combines;    }    public void generate(char[] input, int begin, String output, List<String> list) {        if (begin == input.length) {            list.add(new String(output));            return;        }        String letters = map.get(input[begin]);        for (int i = 0; i < letters.length(); i++) {            output = output + letters.substring(i, i+1);            generate(input, begin+1, output, list);            output = output.substring(0, output.length()-1);        }    }}


0 0
原创粉丝点击