Wednesday, January 7, 2015

LeetCode 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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
public class Solution {
    private List<String> result;
    private Map<Character, String> map;
    private String ret;
    
    public List<String> letterCombinations(String digits) {
        // Backtracking problem
        result = new LinkedList<>();
        
        if (digits.length() == 0)
        {
            result.add("");
            return result;
        }
        
        map = new HashMap<>();
        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");
        
        ret = "";
        
        backTracking(digits, 0);
        
        return result;
    }
    
    private void backTracking(String digits, int i)
    {
        if (i == digits.length()) // Have done the digits traversal
            result.add(ret);
        else
        {
            for (int j = 0; j < map.get(digits.charAt(i)).length(); j++)
            {
                ret += map.get(digits.charAt(i)).charAt(j);
                backTracking(digits, i+1);
                // For substring, the end position is not included.
                ret = ret.substring(0, ret.length()-1);
            }
        }
    }
}

No comments:

Post a Comment