17. Letter Combinations of a Phone Number

网友投稿 667 2022-10-09

17. Letter Combinations of a Phone Number

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. 思路: 经典的backtracking(回溯算法)的题目。当一个题目,存在各种满足条件的组合,并且需要把它们全部列出来时,就可以考虑backtracking了。当然,backtracking在一定程度上属于穷举,所以当数据特别大的时候,不合适。而对于那些题目,可能就需要通过动态规划来完成。   这道题假设输入的是"23",2对应的是"abc",3对应的是"edf",那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来(“ae”,“ad”,“af”),当"edf"穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。

public class Solution { public List letterCombinations(String digits) { String[] table = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; List list = new ArrayList(); letterCombinations(list,digits,"",0,table); return list; } private void letterCombinations (List list, String digits, String curr, int index,String[] table) { if (index == digits.length()) { if(curr.length() != 0) list.add(curr); return; } String temp = table[digits.charAt(index) - '0']; for (int i = 0; i < temp.length(); i++) { String next = curr + temp.charAt(i); letterCombinations(list,digits,next,index+1,table); } }}

Java2

public class Solution { char[][] digit = { {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'}, {'m', 'n', 'o'}, {'p', 'q', 'r', 's'}, {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'} }; public List letterCombinations(String digits) { List res = new ArrayList<>(); if(digits.length()==0) return res; util(digits, 0, "", res); return res; } void util(String digits, int index, String curr, List res) { if(index==digits.length()) { res.add(curr); return; } int num = digits.charAt(index)-'2'; for(int i = 0; i

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:skeletons 首屏渲染-小程序骨架屏动态注入组件(skeleton是什么冬季运动项目)
下一篇:微信小应用-小程序-demo-仿芒果TV(《小程序·巧应用,微信小程序开发实战》)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~