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

题目

按电话上数字与字母的对应关系,如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);        
        }
    }
    
}
相关推荐
CoderCodingNo32 分钟前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
放下华子我只抽RuiKe534 分钟前
机器学习全景指南-直觉篇——基于距离的 K-近邻 (KNN) 算法
人工智能·gpt·算法·机器学习·语言模型·chatgpt·ai编程
kisshuan1239637 分钟前
[特殊字符]【深度学习】DA3METRIC-LARGE单目深度估计算法详解
人工智能·深度学习·算法
sali-tec44 分钟前
C# 基于OpenCv的视觉工作流-章33-Blod分析
图像处理·人工智能·opencv·算法·计算机视觉
Eward-an1 小时前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
一叶落4382 小时前
LeetCode 50. Pow(x, n)(快速幂详解 | C语言实现)
c语言·算法·leetcode
皙然2 小时前
彻底吃透红黑树
数据结构·算法
t198751282 小时前
TOA定位算法MATLAB实现(二维三维场景)
开发语言·算法·matlab
jllllyuz2 小时前
粒子群算法解决资源分配问题的MATLAB实现
开发语言·算法·matlab
renhongxia12 小时前
从模仿到创造:具身智能的技能演化路径
人工智能·深度学习·神经网络·算法·机器学习·知识图谱