本文共 1545 字,大约阅读时间需要 5 分钟。
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.
public class Solution { Map> map; public List letterCombinations(String digits) { map = new HashMap >(); this.map.put(2,new ArrayList (Arrays.asList("a","b","c"))); this.map.put(3,new ArrayList (Arrays.asList("d","e","f"))); this.map.put(4,new ArrayList (Arrays.asList("g","h","i"))); this.map.put(5,new ArrayList (Arrays.asList("j","k","l"))); this.map.put(6,new ArrayList (Arrays.asList("m","n","o"))); this.map.put(7,new ArrayList (Arrays.asList("p","q","r","s"))); this.map.put(8,new ArrayList (Arrays.asList("t","u","v"))); this.map.put(9,new ArrayList (Arrays.asList("w","x","y","z"))); return comb(digits); } public List comb(String digits) { List result = new LinkedList (); if(digits.length() == 0) { result.add(new String("")); } else if(digits.length() == 1) { List ret = new LinkedList (); for(String c:map.get(Integer.parseInt(digits))) ret.add(c); return ret; } else { for(String s : comb(digits.substring(1))) { for(String c:map.get(Integer.parseInt(digits.substring(0,1)))) result.add(c + s); } } return result; } }
转载地址:http://xnuni.baihongyu.com/