17. 电话号码的字母组合

题目:

思路:

【1】利用树遍历的思维,回溯倒推回来即可

代码展示:

//时间1 ms 击败 47.29%
//内存39.6 MB 击败 99.28%
class Solution {
    //将号码字母对应关系存储进Map
    private HashMap<Character, char[]> map = new HashMap<Character, char[]>() {{    //存储为数组更好操作
        put('2', new char[]{'a', 'b', 'c'});
        put('3', new char[]{'d', 'e', 'f'});
        put('4', new char[]{'g', 'h', 'i'});
        put('5', new char[]{'j', 'k', 'l'});
        put('6', new char[]{'m', 'n', 'o'});
        put('7', new char[]{'p', 'q', 'r', 's'});
        put('8', new char[]{'t', 'u', 'v'});
        put('9', new char[]{'w', 'x', 'y', 'z'});
    }};

    public List<String> letterCombinations(String digits) {
        //使用一个集合来存储所有的字母组合结果
        List<String> result = new ArrayList<>();
        if (digits == null || digits.length() == 0) return result;
        StringBuffer buf = new StringBuffer();
        compositionString(digits,0,buf,result);
        return result;
    }

    public void compositionString(String digits , int index,StringBuffer buf, List<String> result){
        // 如果等于了便代表遍历完了,该存储了
        if (index == digits.length()){
            result.add(buf.toString());
            return;
        }
        for (char ch : map.get(digits.charAt(index))){
            buf.append(ch);
            compositionString(digits,index+1,buf,result);
            buf.deleteCharAt(buf.length()-1);
        }
    }
}

 

posted @ 2023-07-03 18:23  忧愁的chafry  阅读(7)  评论(0编辑  收藏  举报