import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Given a string containing digits from 2-9 inclusive, 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.

// Example:

// Input: "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.

class Solution {
    // score:7.24(5ms)
    // tim:O(?)
    // space:O(?)
    public List<String> letterCombinations(String digits) {
        List<String> ret = new ArrayList<>();
        if (digits.length() == 0) {
            return ret;
        }
        backtrack("", 0, digits, ret);
        return ret;
    }

    void backtrack(String prefix, int offset, String digits, List<String> ret) {
        Map<Character, String[]> m = new HashMap<>();
        m.put('2', new String[] { "a", "b", "c" });
        m.put('3', new String[] { "d", "e", "f" });
        m.put('4', new String[] { "g", "h", "i" });
        m.put('5', new String[] { "j", "k", "l" });
        m.put('6', new String[] { "m", "n", "o" });
        m.put('7', new String[] { "p", "q", "r", "s" });
        m.put('8', new String[] { "t", "u", "v" });
        m.put('9', new String[] { "w", "x", "y", "z" });
        if (offset >= digits.length()) {
            ret.add(prefix);
            return;
        }
        String[] letters = m.get(digits.charAt(offset));
        for (int i = 0; i < letters.length; i++) {
            backtrack(prefix + letters[i], offset + 1, digits, ret);
        }
    }
}