一、原题
Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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
二、思路
暴力求解。先求解前两个数字对应数组的笛卡尔积,之后的数字对应的数组与前一次的计算的结果求笛卡尔积。可递归,可循环,这里给出循环解法。
三、代码
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class PhoneNumbers {
public List<String> letterCombinations(String digits) {
String[][] map = new String[][]{
{},
{},
{"a","b","c"},
{"d","e","f"},
{"g","h","i"},
{"j","k","l"},
{"m","n","o"},
{"p","q","r","s"},
{"v","t","u"},
{"y","w","x","z"}};
if(digits == null || "".equals(digits))
return new ArrayList<String>();
else if(digits.length() == 1){
ArrayList result = new ArrayList();
result.add(map[Integer.parseInt(digits)][0]);
result.add(map[Integer.parseInt(digits)][1]);
result.add(map[Integer.parseInt(digits)][2]);
if(map[Integer.parseInt(digits)].length == 4)
result.add(map[Integer.parseInt(digits)][3]);
return result;
}
ArrayList<String> result = new ArrayList<String>();
char[] c= digits.toCharArray();
int[] sa = new int[c.length];
for(int i = 0;i<c.length;i++){
sa[i] = Integer.parseInt(Character.toString(c[i]));
}
String [] r = combine(map[sa[0]],map[sa[1]]);
for(int i = 2;i<sa.length;i++){
r = combine(r,map[sa[i]]);
}
for(String rt :r){
result.add(rt);
}
return result;
}
private String[] combine(String[] a,String[] b){
int l =a.length*b.length;
String[] result = new String[l];
int i =0;
for(String atmp : a){
for(String btmp :b){
result[i] = atmp+btmp;
i++;
}
}
return result;
}
}