电话号码的字母组合

图片说明

思路:回溯

 //主方法
    public List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
        return combinations;
    }

    //回溯子方法
    /**
     *
     * @param combinations  存储结果的list
     * @param phoneMap  数字对应的字符集
     * @param digits  需要解析的数字字符串
     * @param index  表示当前数字字符串上的哪一位(index)
     * @param combination stringBuffer用于字符的拼接
     */
    public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
        if (index == digits.length()) {
            combinations.add(combination.toString());
        } else {

            char digit = digits.charAt(index);
            String letters = phoneMap.get(digit); // 获取这个索引对应的数字字符对应的 key(字符串)
            int lettersCount = letters.length();  //统计 key 的长度

            for (int i = 0; i < lettersCount; i++) {
                combination.append(letters.charAt(i));
                backtrack(combinations, phoneMap, digits, index + 1, combination);
                //删除的是数字串中索引为index对应的 字符串key中的字符(每个数字出一个字符进行组合)
                combination.deleteCharAt(index);
            }
        }
    }
全部评论

相关推荐

04-17 23:48
西北大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务