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.

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()) {
            result.add(sb.toString());
            return;
        }
        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();
            sb.append(search.charAt(i));
            int len2 = sb.length();
            helper(s, start + 1);
            sb.delete(len1, len2);
        }
    }
}
Advertisements