Leetcode 17:电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

java 复制代码
public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return result;
        }
        int index=0;  //记录遍历digits的角标

        //初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串
        String[] str = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        backtracking(str,digits,index);
        System.out.println(result);
        return result;
    }

    //回溯算法
    public void backtracking(String[] str,String digits,int index){

        //1.确定回溯中止条件
        if(index==digits.length()){
            result.add(path.toString());
            return;
        }


        //2.写回溯主体
        int digitsIndex=digits.charAt(index)-'0';  //通过减去'0',得到digits中index对应的角标
        String s=str[digitsIndex];
        for(int i=0;i<s.length();i++){
            path.append(s.charAt(i));  //将遍历字符拼接起来
            backtracking(str,digits,index+1);
            path.deleteCharAt(path.length()-1);   //回溯算法关键一步,删掉最后一个元素
        }
    }
相关推荐
安_4 小时前
如何构建和使用向量索引?HNSW 和 IVF 有什么区别?
python·ai
counting money5 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记6 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
北斗落凡尘6 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
雪碧聊技术7 小时前
安装Python(保姆级教程)
python·版本更新·python下载
++==7 小时前
JSON和Python的 四种核心容器
python·json
Mr.亮先生7 小时前
# 把 DeepSeek 官方 Agent 工作台,直接装进 Windows 启动器里
windows·deepseek·harness
203号居民8 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
张龙6879 小时前
uv 全面指南:比 pip 快 100 倍的 Python 包管理器,从安装到团队落地
后端·python
@HNUSTer9 小时前
Python数据可视化科技图表绘制系列教程(八)
python·数据可视化·科技论文·专业制图·科研图表