LeetCode 17 电话号码的字母组合 简单递归

// 用map将数字字母与字符串进行映射,然后深搜
// 注意,有输入为空
 
class Solution {
    public List<String> res = new ArrayList<>();
    HashMap<Character, String> map = new HashMap<>();
    public List<String> letterCombinations(String digits){

        if (digits == null || digits.length() == 0) return res;
        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");
        dfs(digits,0,"");
        return res;
    }

    public void dfs(String digits, int ind, String s){
        if (ind == digits.length()){
            res.add(s);
            return ;
        }
        String x = map.get(digits.charAt(ind));
        for(int i = 0; i < x.length(); i++){
            String u = s + x.charAt(i);
            dfs(digits, ind + 1, u);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/TIMELIMITE/article/details/89362776
今日推荐