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 { char[][] a = {{},{},{'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<String> letterCombinations(String digits) { if(digits.length() == 0){ return new ArrayList<String>(); } if(digits.length() == 1){ List<String> result = new ArrayList<String>(); int i = Integer.parseInt(digits); for(char c : a[i]){ result.add(Character.toString(c)); } return result; } int j = Integer.parseInt(digits.substring(0,1)); List<String> res = new ArrayList<String>(); for(char c : a[j]){ for(String ss : letterCombinations(digits.substring(1))){ res.add(c+ss); } }return res; }}
附上大神的遞迴,速度很快~
public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<String>(); if(!digits.isEmpty()) { helper(digits, "", 0, list); } return list;}public void helper(String digits, String combo, int position, List<String> list) { if(position == digits.length()) { list.add(combo); return; } String[] letters = getMapping(digits.charAt(position)); for(int i = 0; i < letters.length; i++){ helper(digits, combo + letters[i], position + 1, list); }}public String[] getMapping(char c) { switch (c) { case '2': return new String[] {"a", "b", "c"}; case '3': return new String[] {"d", "e", "f"}; case '4': return new String[] {"g", "h", "i"}; case '5': return new String[] {"j", "k", "l"}; case '6': return new String[] {"m", "n", "o"}; case '7': return new String[] {"p", "q", "r", "s"}; case '8': return new String[] {"t", "u", "v"}; case '9': return new String[] {"w", "x", "y", "z"}; } return new String[] {};}