leetcode 算法 17. Letter Combinations of a Phone Number

来源:互联网 发布:阿里云怎么搭建vpn免流 编辑:程序博客网 时间:2024/06/05 13:27

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"].

i=0 -> result=combine("abc", [""]) ---> [a,b,c];

i=1 -> result=combine("def", [a,b,c]) ---> [ad,bd,cd, ae,be,ce, af,bf,cf];


``` java
public List<String> letterCombinations(String digits) { 
String digitletter[] =  {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> result =new ArrayList<String>();
if (digits.length()==0) return result;
result.add("");//这一段让下面 List<String> l不为空,直接填填充
for (int i = 0; i < digits.length(); i++) {
result = combine( digitletter[digits.charAt(i)-'0'],result);
}
return result;        
 }
public static List<String> combine(String digit, List<String> l) {
List<String> result = new ArrayList<String>();
for (int i = 0; i < digit.length(); i++) {
for (String x : l) {
result.add(x+digit.charAt(i));
}
}
return result;
}

```

原创粉丝点击