Java [leetcode 17]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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
解题思路:
递归法解题之。从第一个字符串开始确认结果,然后递归地确认余下各项结果。
参考博客:http://blog.csdn.net/china_wanglong/article/details/38495355
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Solution { public List<String> letterCombinations(String digits) { List<String> result = new ArrayList<String>(); String[] map = new String[] { "" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" }; char [] tmp = new char [digits.length()]; if (digits.length() == 0 ) return result; rec(digits, 0 , tmp, map, result); return result; } public void rec(String digits, int index, char [] tmp, String[] map, List<String> result){ if (index == digits.length()){ result.add( new String(tmp)); return ; } char tmpChar = digits.charAt(index); for ( int i = 0 ; i < map[tmpChar - '0' ].length(); i++){ tmp[index] = map[tmpChar - '0' ].charAt(i); rec(digits, index + 1 , tmp, map, result); } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步