letter combinations of a phone number(回溯)

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

        这道题的思路很简单,假设输入的是"23",2对应的是"abc",3对应的是"edf",那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来("ae","ad","af"),当"edf"穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。

遍历当前数字对应的字符,对于每个字符,都要添加到字符串中,然后遍历剩下的数字,并添加剩下数字的字符(这个继续递归,控制index),所以有个指针指向当前数字,这就是index

class Solution {
    /*
        这道题的思路很简单,假设输入的是"23",2对应的是"abc",3对应的是"edf",那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来("ae","ad","af"),当"edf"穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。
    */
    String[] map=new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    public List<String> letterCombinations(String digits) {
        
        List<String> list=new ArrayList<>();
        if(digits==null||digits.length()==0) return list;
        helper(list,"",digits,map,0);
        return list;
        
    }
    
    /*
    各个参数意思:current 表示当前字符串(用于添加到list中的,结果串),index:digits中的第几位,用于判断
    */
    public void helper(List<String> list,String current,String digits,String[] map,int index){
        //最后一层的退出条件,index从0开始的,当等于digits的长度时,也就是所有数字都遍历过了,可以结束了
        if(index==digits.length()){
            if(current.length()!=0) list.add(current);
            return ;
        }
        
        //index不是最后一层,那就遍历这个数字对应的字母,并添加剩下数字对应的字母
        String s=map[digits.charAt(index)-'0'];
        //遍历当前数字对应的字符,并添加剩下数字的字符(这个继续递归,控制index)
        for(int i=0;i<s.length();i++){
            String next=current+s.charAt(i);//这里用next,而不是直接用current ,因为这里current不能被修改,因为遍历时每个字母都是单独加在current上
           //进入下一层
            helper(list,next,digits,map,index+1);
        }
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8094262.html