题目地址:
中文:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
英文:https://leetcode.com/problems/letter-combinations-of-a-phone-number/
题目描述:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
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 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range [‘2’, ‘9’].
思路:
输入2-9的数字,按返回各种可能的字母组成。
递归实现比较方便。
题解:
class Solution {
Map<String,String> map= new HashMap<String, String>(){
{
put("2","abc");
put("3","def");
put("4","ghi");
put("5","jkl");
put("6","mno");
put("7","pqrs");
put("8","tuv");
put("9","wxyz");
}
};
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits==""||digits.length()==0) return list;
add(digits,"");
return list;
}
public void add(String str,String s){
if(str==""||str.length()==0) {list.add(s);return;}
for(int j=0;j<map.get(str.substring(0,1)).length();j++){
String temp = String.valueOf(map.get(str.substring(0,1)).charAt(j));
s += temp;
add(str.substring(1),s);
s = s.substring(0,s.length()-1);
}
}
}