Problem

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.png

Example

Given "23"
Return ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

Note

DFS做法:
在主函数中,创建手机按键的String array,创建StringBuilder sb,创建结果数组res.
在helper函数中,用index去标记原字符串digits中正被遍历的那一位。
当index到达最后一位,也就是digits.length()的时候:如果此时StringBuilder长度非0,就加入结果数组res。
否则,找出当前位在table中的对应字符串cur,然后遍历cur的每一位:每一位的字符放入sb,调用helper函数,再删除最末位继续遍历。

Solution

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        String[] table = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        StringBuilder sb = new StringBuilder();
        helper(digits, 0, table, sb, res);
        return res;
    }
    public void helper(String digits, int index, String[] table, StringBuilder sb, List<String> res) {
        if (index == digits.length()) {
            if (sb.length() != 0) res.add(sb.toString());
        }
        else {
            String cur = table[digits.charAt(index)-'0'];
            for (int i = 0; i < cur.length(); i++) {
                sb.append(cur.charAt(i));
                helper(digits, index+1, table, sb, res);
                sb.deleteCharAt(sb.length()-1);
            }
        }
    }
}

Update 2018-03

public class Solution {
    public List<String> letterCombinations(String digits) {
        
        //format output
        List<String> res = new ArrayList<>();
        
        //input null/empty checks
        if (digits == null || digits.length() == 0) return res;
        
        //create the num-to-char mapping
        String[] map = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        
        //initialize an empty string representing a subset
        String str = "";
        
        //call DFS
        dfs(digits, 0, map, str, res);
        
        return res;
    }
    public void dfs(String digits, int index, String[] map, String str, List<String> res) {
        
        //stop the path when such condition met
        if (str.length() == digits.length()) res.add(str);
        
        //DFS implementation
        else {
            
            //get node
            String cur = map[digits.charAt(index)-'0'];
            
            //exhaustive search
            for (int i = 0; i < cur.length(); i++) {
                //visit and select the current node
                str += cur.charAt(i);
                
                //use index+1 to DFS the next node
                dfs(digits, index+1, map, str, res);
                
                //backtracking to traverse the unvisited nodes
                str = str.substring(0, str.length()-1);
            }
        }
        
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论