【Leetcode-17】Letter Cominations of a Phone Number
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.
使用回溯解决这个问题
class Solution17 {
Map<String,String> map=new HashMap<String,String> ();
List<String> list=new ArrayList<String>();
public List<String> letterCombinations(String digits) {
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");
backtrack("",digits);
if(digits.length()==0){
return new ArrayList<String>();
}
return list;
}
private void backtrack(String combination,String next_digits) {
if(next_digits.length()==0) {
list.add(combination);
}
else {
//取下一个数
String str=map.get(next_digits.substring(0,1));
int len=str.length();
for(int i=0;i<len;i++) {
backtrack(combination+str.substring(i,i+1), next_digits.substring(1));
/*
* String s=combination;
* combination+=str.substring(i,i+1);
* backtrack(combination, next_digits.substring(1));
* combination=s;
*/
}
}
}
}