题目原文:
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”].
题目大意:
给出一个九键键盘,和数字序列,求出所有可能的对应字母组合。
题目分析:
还是一个暴力的回溯法,使用backtrack(List list, String digits, String currentLetter, int index)维护搜索过程,其中list是字母组合的列表,digits是数字序列,currentLetter是当前的搜索结果,index记录digits串中该搜索的位置。
源码:(language:java)
public class Solution {
private String[][] letters = new String[][] {
{" "},
{},
{"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) {
List<String> list = new ArrayList<String>();
if(digits.length() > 0)
backtrack(list, digits, new String(), 0);
return list;
}
private void backtrack(List<String> list, String digits, String currentLetter, int index) {
if(index == digits.length()) {
list.add(currentLetter);
return;
}
else {
int num = digits.charAt(index) -'0';
for(int i = 0; i < letters[num].length; i++) {
currentLetter+=letters[num][i];
backtrack(list, digits, currentLetter, index+1);
currentLetter = currentLetter.substring(0,currentLetter.length()-1);
}
}
}
}
成绩:
1ms,beats 46.02%,众数1ms,53.98%