LeetCode17.电话号码的字母组合

写这题的时候没有啥DFS思路,感觉还是DFS没刷明白,还需要多提高
参考链接:
【还得用回溯算法!| LeetCode:17.电话号码的字母组合-哔哩哔哩】 https://b23.tv/oTuy71C

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> ans=new ArrayList<>();
        if(digits==null||digits.length()==0){
            return ans;    
        }
        char[] ch=digits.toCharArray();
        Map<Integer,String> map=new HashMap<>();
        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");
        StringBuilder sb=new StringBuilder();
        dfs(ch,map,ans,sb,0);
        return ans;
    }
    public void dfs(char[] ch,Map<Integer,String> map,List<String> ans,StringBuilder sb,int index){
        
        if(index==ch.length){
            ans.add(sb.toString());
            // sb.setLength(0);
            return;    
        }

        String curStr = map.get(ch[index]-'0');
        int n=curStr.length();

        for(int i=0;i<n;++i){
            sb.append(curStr.charAt(i));
            dfs(ch,map,ans,sb,index+1);
            sb.deleteCharAt(sb.length()-1);
        }

    }
    
}

你可能感兴趣的:(LeetCode题库,深度优先,DFS,回溯)