题解 | #电话号码的字母组合#

电话号码的字母组合

https://www.nowcoder.com/practice/2d3a1e71112546ac836700ccbd1f5936

import java.util.*;


public class Solution {

    ArrayList<String> ret;
    StringBuilder path ;
    String[] hash = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    //存储数字与字母的映射关系
    public ArrayList<String> phoneNumber (String num) {
        // write code here
        ret = new ArrayList<>();
        path = new StringBuilder();
        dfs(num,0);
        return ret;
    }

    public void dfs(String num,int pos){
        //递归子函数,pos记录翻译到了能够数字
        if(pos==num.length()){
            //递归到了叶子节点
            ret.add(new String (path));
            return;
        }
        
        
        //得到当前数字对应的字符,递归加入该字符
        String cur = hash[num.charAt(pos)-'0'];
        //遍历每个字母,因为第一次有三种选择
        for(int i=0;i<cur.length();i++){
            //将该字符加入path
            path.append(cur.charAt(i));
            //dfs下一个数字
            dfs(num,pos+1);

            //回溯
            path.deleteCharAt(path.length()-1);
        }

    }
}

全部评论

相关推荐

专业码bug百年:整个宇宙为你而闪烁
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务