题目链接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/
解题思路:
用回溯法求解
经典的backtracking(回溯算法)的题目。当一个题目,存在各种满足条件的组合,并且需要把它们全部列出来时,就可以考虑backtracking了。当然,backtracking在一定程度上属于穷举,所以当数据特别大的时候,不合适。而对于那些题目,可能就需要通过动态规划来完成。
这道题的思路很简单,假设输入的是"23",2对应的是"abc",3对应的是"edf",那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来("ae","ad","af"),当"edf"穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。
1 class Solution { 2 public List<String> letterCombinations(String digits) { 3 4 List<String> res = new ArrayList<String>(); 5 //先把表从0-9列出来 6 String [] table = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 7 //index从0开始, 8 int index = 0; 9 //当前字符肯定为空 10 buildResult(res,digits,"",0,table); 11 return res; 12 13 14 } 15 public void buildResult(List<String> res ,String digits,String curr,int index,String[] table) 16 { 17 if(index == digits.length()) 18 { 19 if(curr.length()!=0) 20 res.add(curr); 21 return; 22 } 23 24 //找到数字对应的字符串 25 String temp = table[digits.charAt(index) - '0']; 26 27 for(int i=0;i<temp.length();i++) 28 { 29 String next = curr+temp.charAt(i); 30 31 buildResult(res,digits,next,index+1,table); 32 } 33 34 } 35 }