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"].
思路:采用回溯法
import java.util.HashMap;
import java.util.ArrayList;
public class Solution {
ArrayList<String> res = new ArrayList<>();
String temp = "";
public ArrayList<String> letterCombinations(String digits) {
if(digits.length() == 0 || digits == null){
res.add("");
return res;
}
//将数字以及对应的字母以key-value存入map集合中,以便于读取
HashMap<Character,String> map=new HashMap<>();
map.put('0',""); map.put('1',"");map.put('2',"abc");
map.put('3',"def");map.put('4',"ghi");map.put('5',"jkl");
map.put('6',"mno"); map.put('7',"pqrs");map.put('8',"tuv");
map.put('9',"wxyz");
res = combine(digits, 0, map);
return res;
}
//回溯法
public ArrayList<String> combine(String digits, int start, HashMap<Character,String> map){
//达到字母组合的总数目,返回结果
if(start == digits.length()){
res.add(temp);
return res;
}
String str = map.get(digits.charAt(start));
for(int i = 0; i < str.length(); i++){
//拼接字母,形成字母组合
temp = temp + str.charAt(i);
//start+1,不断将从每个数字中获取一个字母,并把这些字母拼接起来
combine(digits, start + 1, map);
//剔除最后一个字母,加入新的字母,产生新的组合
temp = temp.substring(0, temp.length() - 1);
}
return res;
}
}