Question:
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"].
利用广度优先对所有字符进行排列组合。
java代码如下:
public class Solution {
String map[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> combine(List<String> res, String digits, int i){
if(i < digits.length()){
List<String> temp = new ArrayList();
for(int k = 0; k < res.size(); k ++){
String str = res.get(k);
for(int j = 0; j < map[digits.charAt(i) - '2'].length(); j ++){
temp.add(str + map[digits.charAt(i) - '2'].charAt(j));
}
}
return combine(temp, digits, i+1);
}
else{
return res;
}
}
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList();
if(digits.length() < 1)
return res;
res.add("");
return combine(res, digits, 0);
}
}
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"].
利用广度优先对所有字符进行排列组合。
java代码如下:
public class Solution {
String map[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> combine(List<String> res, String digits, int i){
if(i < digits.length()){
List<String> temp = new ArrayList();
for(int k = 0; k < res.size(); k ++){
String str = res.get(k);
for(int j = 0; j < map[digits.charAt(i) - '2'].length(); j ++){
temp.add(str + map[digits.charAt(i) - '2'].charAt(j));
}
}
return combine(temp, digits, i+1);
}
else{
return res;
}
}
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList();
if(digits.length() < 1)
return res;
res.add("");
return combine(res, digits, 0);
}
}