17. Letter Combinations of a Phone Number | Java最短代码实现

原题链接: 17. Letter Combinations of a Phone Number

【思路】

本题是回溯算法的基本应用。将整数值和对应的字母存入hashmap。

1.逐个取出digitals里的值,作为key在hashmap中找到val,取出val中的一个字符,并拼接在temp中

2.循环上述过程,直到digitals的最后一个字符,然后回溯:

    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if (digits.length() == 0) return result;
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(0, "");
        map.put(1, "");
        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");
        searchCombinations(digits, 0, result, "", map);
        return result;
    }
    public void searchCombinations(String digits, int index, List<String> result, String temp, HashMap<Integer, String> map) {
        if (index == digits.length()) {
            result.add(temp);
            return;
        }
        String chars = map.get(digits.charAt(index) - '0');
        for (int i = 0; i < chars.length(); i++) {
            temp += chars.charAt(i);
            searchCombinations(digits, index + 1, result, temp, map);
            temp = temp.substring(0, temp.length() - 1);
        }
    }
25 / 25  test cases passed. Runtime: 1 ms  Your runtime beats 46.02% of javasubmissions.
欢迎优化!

你可能感兴趣的:(backtracking)