17 Letter Combinations of a Phone Number

Given a string containing digits from2-9inclusive, 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. Note that 1 does not map to any letters.

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution {
    public String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    public List<String> letterCombinations(String digits) {
        List<String> ans = new ArrayList<>();
        if (digits == null || digits.length() == 0){
            return ans;
        }
        dfs(ans, digits, 0,"");
        return ans;
    }
    public void dfs(List<String> ans, String digits, int startIdx, String combination) {
        if (startIdx == digits.length()) {
            ans.add(combination);
            return;
        }

        String letters = mapping[digits.charAt(startIdx)-'0'];
        for (int i = 0; i < letters.length(); i++) {
            dfs(ans, digits, startIdx + 1, combination + letters.charAt(i));
        }
    }

}

results matching ""

    No results matching ""