17. Letter Combinations of a Phone Number - Medium

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.

 

use DFS: n recursion levels, in each recursion level, there're at most 4 states to consider about

time = O(4 ^ n), space = O(n)

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if(digits.length() == 0) {
            return res;
        }
        String[] keypads = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        dfs(digits, 0, keypads, new StringBuilder(), res);
        return res;
    }
    
    public void dfs(String s, int idx, String[] keypads, StringBuilder sb, List<String> res) {
        if(idx == s.length()) {
            res.add(sb.toString());
            return;
        }
        int cur = Integer.parseInt(s.substring(idx, idx + 1));
        for(int i = 0; i < keypads[cur].length(); i++) {
            sb.append(keypads[cur].charAt(i));
            dfs(s, idx + 1, keypads, sb, res);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}

 

posted @ 2019-08-08 09:48  fatttcat  阅读(118)  评论(0编辑  收藏  举报