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"].
这道题目的解题思路有点类似于DFS(depth first search)算法的主要思想,如果对这道题目无从下手,个人觉得可以先去看一看DFS算法,然后回过头来做这道题目。我没有去了解有没有其他的一些优秀的解题思想,现在将我的这道题目的解题思想讲解一下,大家互相交流。
public class Solution
{
public List<String> letterCombinations(String digits)
{
//1.将每个值所对应的字符集存放到map中
Map<Integer, String> map = new HashMap<>();
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");
map.put(0, "");
//存放结果值
ArrayList<String> result = new ArrayList<>();
if (digits.length() == 0 || digits == null)
return result;
//辅助存储
ArrayList<Character> temp = new ArrayList<>();
getString(digits, temp, result, map);
return result;
}
public void getString(String digits, ArrayList<Character> temp, ArrayList<String> result, Map<Integer, String> map)
{
if (digits.length() == 0)
{
char[] array = new char[temp.size()];
for (int i = 0; i < temp.size(); i++)
{
array[i] = temp.get(i);
}
result.add(String.valueOf(array));
return;
}
Integer intValue = Integer.valueOf(digits.substring(0, 1));
String letters = map.get(intValue);
for (int i = 0; i < letters.length(); i++)
{
temp.add(letters.charAt(i));
getString(digits.substring(1), temp, result, map);
temp.remove(temp.size() - 1);
}
}
}