算法训练:电话号码的字母组合(回溯求解)java

问题描述:
在这里插入图片描述
分析问题:
由问题可知,每一个按键都有着对应得映射关系,因此可以将按键的值作为key,将对应的小写字母字符串作为值存放在哈希表中。通过访问按键的值对相应的字符串的逐个字符进行遍历,采用深度遍历的思想,将访问到的字符进行组合,并将组合的结果存放在一个数组中,每一个组合完成之后将数组加入一个集合之中,最后返回该存放了不同值的集合。

在这里插入图片描述
代码如下:

class Solution {
    
    
    public List<String> letterCombinations(String digits) {
    
    
        List<String> combinations=new ArrayList<>();
         if(digits.length()==0){
    
    
            return combinations;
        }       
        Map<Character,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");
        backtrace(combinations,map,digits,0,new StringBuffer());
        return combinations;
    }
    public void backtrace(List<String> combinations,Map<Character,String> map,String digits,int index,StringBuffer tempcode){
    
    
        if(index==digits.length()){
    
    
            combinations.add(tempcode.toString());
        }
        else{
    
    
            char digit = digits.charAt(index);
            String letters = map.get(digit);
            int lettersCount = letters.length();
            //此处的letters为null,尚待解决           
            for(int i=0;i< lettersCount;i++){
    
    
                tempcode.append(letters.charAt(i));
                backtrace(combinations,map,digits,index+1,tempcode);
                tempcode.deleteCharAt(index);
            }
        }
    }
}

时间复杂度:O(3ⁿ+4ⁿ);3是指其中对应了3个小写字母的数字,4指对应了4个小写字母的数字
空间复杂度:O(m+n),因为数据结构采用了哈希表;

猜你喜欢

转载自blog.csdn.net/weixin_45394002/article/details/108236390
今日推荐