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.
Time: O(3^N)
class Solution { private String[] letters = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { List<String> res = new ArrayList<>(); if (digits == null || digits.length() == 0) { return res; } helper(res, "", digits, 0); return res; } private void helper(List<String> res, String s, String digits, int index) { if (s.length() == digits.length()) { res.add(s); return; } String curLetter = letters[digits.charAt(index) - '0']; // loop through current letters[index] for (int i = 0; i < curLetter.length(); i++) { helper(res, s + curLetter.charAt(i), digits, index + 1); } } }