电话号码的字母组合-算法

题目

按电话上数字与字母的对应关系,如2={a,b,c},3={d,e,f}等,给定一串数字如267,则求出abc,mno,qprs的所有组合,如amq,amp...cor,cos等

思路

遍历都可以用回溯的方式尝试解决,每次遍历结束后,将上一层元素删除,满足长度,则加入到结果中

复制代码
public List<String> letterCombinations(String digits){
    List<String> combinations = new ArrayList<>();
    if(digits.length()==0){
        return combinations;    
    }
    Map<Character,String> digitLetterMap = new HashMap<>(){{
       put('2',"abc");
       put('3',"def");
       put('4',"ghi");
       put('5',"jkl");
       put('6',"mno");
       put('7',"qprs");
       put('8',"tuv");
       put('9',"wxyz");  
    }};
    backtrack(combinations,digitLetterMap,digits,0,new StringBuffer());
    return combinations;
}

public void backtrack(List<String> combinations,
                        Map<Character,String> digitLetterMap,
                        String digits,
                        int index,StringBuffer combination){
    if(index == digit.legnth()){
        combinations.add(combination.toString());
    }else{
        char digit = digits.charAt(index);
        String letters = digitLetterMap.get(digit);
        int letterCount = letters.legnth();
        for(int i=0;i<letterCount;i++){
            combination.append(letters.charAt(i));
            backtrack(combinations,digitLetterMap,digits,index+1,combination);
            combination.deleteCharAt(index);        
        }
    }
    
}
相关推荐
2401_841495642 小时前
【计算机视觉】基于复杂环境下的车牌识别
人工智能·python·算法·计算机视觉·去噪·车牌识别·字符识别
Jonkin-Ma2 小时前
每日算法(1)之单链表
算法
晚风残3 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer
杨云强3 小时前
离散积分,相同表达式数组和公式
算法
地平线开发者3 小时前
征程 6 | BPU trace 简介与实操
算法·自动驾驶
满天星83035773 小时前
【C++】AVL树的模拟实现
开发语言·c++·算法·stl
Lris-KK4 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
麦麦鸡腿堡4 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
zy_destiny4 小时前
【工业场景】用YOLOv8实现抽烟识别
人工智能·python·算法·yolo·机器学习·计算机视觉·目标跟踪
坚持编程的菜鸟4 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵