17. Letter Combinations of a Phone Number

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"].

Although the above answer is in lexicographical order, your answer could be in any order you want.

public class Solution {
    private int[] num = new int[]{2,3,4,5,6,7,8,9};
    private String[] letter = new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    private HashMap<Integer, String> map = new HashMap<>();
    List<String> result = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) return result;
        for (int i = 0; i < num.length; i++) {
            map.put(num[i], letter[i]);
        helper(digits, 0);
        return result;
    private void helper(String s, int start) {
        if (start == s.length()) {
        int digit = Integer.valueOf(s.charAt(start) - '0');
        String search = map.get(digit);
        for (int i = 0; i < search.length(); i++) {
            int len1 = sb.length();
            int len2 = sb.length();
            helper(s, start + 1);
            sb.delete(len1, len2);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s