回溯法(5)
来源:互联网 发布:java面向对象测试题 编辑:程序博客网 时间:2024/06/05 17:16
原题:
/** * Created by gouthamvidyapradhan on 09/03/2017. * Given a digit string, return all possible letter combinations that the number could represent. * <p> * A mapping of digit to letters (just like on the telephone buttons) is given below. * 1 2(abc) 3(def) * 4(ghi) 5(jkl) 6(mno) * 7(pqrs) 8(tuv) 9(wxyz) * <p> * <p> * 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. */
答案:
public class LetterPhoneNumber { private String[] NUMBER_ALPHA = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; /** * Main method * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { List<String> result = new LetterPhoneNumber().letterCombinations("23"); result.forEach(System.out::println); } private List<String> letterCombinations(String digits) { if (digits == null || digits.isEmpty() || digits.contains("1") || digits.contains("0")) return new ArrayList<>(); List<String> prev = new ArrayList<>(); prev.add(""); for (int i = digits.length() - 1; i >= 0; i--) { String str = NUMBER_ALPHA[Integer.parseInt(String.valueOf(digits.charAt(i)))]; List<String> newList = new ArrayList<>(); for (int j = 0, l = str.length(); j < l; j++) { for (String s : prev) { s = str.charAt(j) + s; newList.add(s); } } prev = newList; } return prev; }}
阅读全文
0 0
- 回溯法(5)
- 回溯法(1)
- 回溯法(2)
- (八)回溯法
- 回溯法(1)
- 回溯法(1)
- 回溯法(一)
- 回溯法(DFS)
- 回溯法(1)
- 回溯法(2)
- 回溯法(3)
- 回溯法(4)
- 回溯法(6)
- 回溯法(7)
- (回溯法) 数据结构_回溯法求解迷宫路径
- 01背包------回溯法(包括回溯法讲解)
- 集装箱问题(回溯法)
- uva539(卡坦岛)-回溯法
- 进程与线程的区别与联系
- 轮播图
- PCB制作中的过孔
- problems encountered during text search
- VS2017写代码时几个常用的快捷键
- 回溯法(5)
- byte数组的转化
- Android和iOS的名片拍照扫描识别功能sdk
- 第八周项目三 对矩阵压缩存储的实现与应用(2)
- CListCtrl控件删除多个选中行时问题的解决
- web.xml中配置的classpath含义
- 数据库学习---3
- esayui--下拉列表框只能选择当前数据往后的(不可逆的)
- 时间管理