Letter Combinations of a Phone Number

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.

200px-Telephone-keypad2.svg

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.

题解:

电话号码刚好是一串从0到9的数字,所以我们用一个String数组保存映射。

后面的字符组合用回溯法做就可以了。

 

public class Solution {
    public List<String> letterCombinations(String digits) {
        ArrayList<String> result = new ArrayList<String>();
        if (digits == null || digits.length() == 0) {
            return result;
        }
        String[] phone = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        helper(phone, digits, new StringBuilder(), result);
        return result;
    }

    private void helper(String[] phone, String digits, StringBuilder sb, ArrayList<String> result) {
        if (sb.length() == digits.length()) {
            result.add(sb.toString());
            return;
        }
        for (char c : phone[digits.charAt(sb.length()) - '0'].toCharArray()) {
            sb.append(c);
            helper(phone, digits, sb, result);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}