17. 电话号码的字母组合

17. 电话号码的字母组合

回溯

class Solution {
    List<String> res = new ArrayList<>();
    StringBuilder path = new StringBuilder();
    String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public List<String> letterCombinations(String digits) {
        if(digits.length() == 0) return res;
        backtrack(digits, 0);
        return res;
    }

    void backtrack(String digits, int ind){
        if(ind == digits.length()){
            res.add(path.toString());
            return;
        }

        String str = map[digits.charAt(ind) - '0'];
        for(char c : str.toCharArray()){
            path.append(c);
            backtrack(digits, ind + 1);
            path.deleteCharAt(path.length() - 1);
        }
    }
}

对于返回结果列表是字符串类型的 ,放在参数中的写法如下

class Solution {
    List<String> res = new ArrayList<>();
    String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public List<String> letterCombinations(String digits) {
        if(digits.length() == 0) return res;
        backtrack(digits, 0, "");
        return res;
    }

    void backtrack(String digits, int ind, String path){
        if(ind == digits.length()){
            res.add(path.toString());
            return;
        }

        String str = map[digits.charAt(ind) - '0'];
        for(char c : str.toCharArray()){
            backtrack(digits, ind + 1, path + c);
        }
    }
}

HashMap 的版本

class Solution {
    List<String> res = new ArrayList<>();
    HashMap<Character, String> map = new HashMap<>(){{put('2', "abc"); put('3', "def"); put('4', "ghi"); put('5', "jkl"); put('6', "mno"); put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");}};

    public List<String> letterCombinations(String digits) {
        if(digits.length() == 0) return res;
        backtrack(digits, 0, "");
        return res;
    }

    void backtrack(String digits, int index, String path){
        if(index == digits.length()){
            res.add(path);
            return;
        }

        char c = digits.charAt(index);
        String str = map.get(c);
        for(char d : str.toCharArray()){
            backtrack(digits, index + 1, path + d);
        }
    }
}
HashMap<Character, String> map = new HashMap<>(){{put('2', "abc"); put('3', "def"); put('4', "ghi"); put('5', "jkl"); put('6', "mno"); put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");}};

上述语法解释: 【Java 简洁初始化类】匿名内部类和实例初始化块

你可能感兴趣的:(算法,算法)