LEETCODE 17 Letter Combinations of a Phone Number (JAVA题解)

来源:互联网 发布:通达信的行情软件 编辑:程序博客网 时间:2024/06/06 00:03

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

原题链接如上:


题意解析:大家应该用过移动设备上的输入法吧,如果用九宫键进行输入的话,按数字键23,会出现如下英文字母的组合 

["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
题目是说,给出一个由数字组成的字符串,例如“23456”,让你给出所有可能的英文字母组合。


解题思路:

以23为例,第一个字母可能为a,也可能为b和c,那么我们暂且先尝试a,第二个字母可能是d,也可能是e和f,我们先尝试d,然后再尝试e,然后在尝试f,之后回退到第一个字母,刚才a已经尝试过了,所以这次要尝试b。。。。。。。这种回退的思想,只有递归才能实现(或者用栈模拟递归的活动轨迹)


题解代码:

<span style="font-size:24px;">public List<String> letterCombinations(String digits) {        List<String> result=new ArrayList<String>();        Map<Character,String> dsMap=new HashMap<Character,String>();        int[] choses=new int[digits.length()];                //create digit letter mapping        dsMap.put('2',"abc");        dsMap.put('3',"def");        dsMap.put('4',"ghi");        dsMap.put('5',"jkl");        dsMap.put('6',"mno");        dsMap.put('7',"pqrs");        dsMap.put('8',"tuv");        dsMap.put('9',"wxyz");                //inizialing the choses array        for(int i=0;i<choses.length;i++){            choses[i]=-1;        }                search(choses,0,result,dsMap,digits);        return result;    }        public static void search(int[] choses,int index,List<String> result,Map<Character,String> dsMap,String digits){        if(index==choses.length){            StringBuffer temp=new StringBuffer();            for(int i=0;i<digits.length();i++){                String str=(String)dsMap.get(digits.charAt(i));                temp.append(str.charAt(choses[i]));            }            if(!temp.toString().equals("")){                result.add(temp.toString());            }            return;        }        choses[index]=0;        search(choses,index+1,result,dsMap,digits);        choses[index]=1;        search(choses,index+1,result,dsMap,digits);        choses[index]=2;        search(choses,index+1,result,dsMap,digits);        if(((String)dsMap.get(digits.charAt(index))).length()==4){            choses[index]=3;            search(choses,index+1,result,dsMap,digits);        }    }</span>


0 0
原创粉丝点击