标签:
问题描述:
Given a digitstring, return all possible letter combinations that the number couldrepresent.
A mapping of digitto letters (just like on the telephone buttons) is given below.
Input:Digit string"23"
Output:["ad", "ae", "af", "bd","be", "bf", "cd", "ce","cf"].
Note:
Although the above answer is in lexicographical order, your answer could be inany order you want.
问题分析:简单的树的遍历问题;
代码:
解法一:
/**解法一:直接实现树的遍历*/ public class Solution { public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<>(); if(digits == null || digits.length() == 0) return result; char[][] chars = {{},//0 {},//1 {'a','b','c'},//2 {'d','e','f'},//3 {'g','h','i'},//4 {'j','k','l'},//5 {'m','n','o'},//6 {'p','q','r','s'},//7 {'t','u','v'}, //8 {'w','x','y','z'} //9 }; char[] temp_str = new char[digits.length()]; DFS(digits, 0, chars, temp_str, result); return result; } /*深度优遍历算法*/ /*参数: @params: digits:输入电话号码参数; depth:遍历的树的深度; chars:每个数字对应字符数组; temp_str:临时结果char数组; result:结果List; */ private void DFS(String digits, int depth, char[][] chars, char[] temp_str, List<String> result) { //递归的重点 if(depth == digits.length()) { result.add(new String(temp_str)); return; } int digit = 0; while((digit = digits.charAt(depth) - '0') < 2) { depth++; } for(int i = 0; i < chars[digit].length; i++) { //更新temp_str temp_str[depth] = chars[digit][i]; DFS(digits, depth + 1, chars, temp_str, result); } } }
解法二:递归实现 public class Solution { public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<>(); if(digits == null || digits.length() == 0) return result; char[][] chars = {{},//0 {},//1 {'a','b','c'},//2 {'d','e','f'},//3 {'g','h','i'},//4 {'j','k','l'},//5 {'m','n','o'},//6 {'p','q','r','s'},//7 {'t','u','v'}, //8 {'w','x','y','z'} //9 }; //设置每一次循环选取的位置数组 int[] index = new int[digits.length()]; int k = digits.length() - 1; while(k >= 0) { //临时结果数组 StringBuffer temp_str = new StringBuffer(); for(int i = 0; i < digits.length(); i++) { int j = digits.charAt(i) - '0'; if(j >= 2) { temp_str.append(chars[j][index[i]]); } } result.add(new String(temp_str)); //每次都从最后一位开始更新 k = digits.length() - 1; //更新index值 while(k >= 0) { if(index[k] < (chars[digits.charAt(k)-'0'].length - 1) ) { index[k]++; break; //注意这里的break,当更新完一个值后,就要注意退出 } else { index[k] = 0; k--; } } } return result; } }
leetcode-17 Letter Combinations of a Phone Number
标签:
原文地址:http://blog.csdn.net/woliuyunyicai/article/details/45248613