题目链接
回溯
class Solution {List<String> res = new ArrayList<String>();StringBuilder str = new StringBuilder();HashMap<String, String> Sites = new HashMap<String, String>();public List<String> letterCombinations(String digits) {Sites.put("0","");Sites.put("1","");Sites.put("2","abc");Sites.put("3","def");Sites.put("4","ghi");Sites.put("5","jkl");Sites.put("6","mno");Sites.put("7","pqrs");Sites.put("8","tuv");Sites.put("9","wxyz");if(digits == null || digits.length() == 0){return res;}backtracking(digits,0);return res;}public void backtracking(String digits,int index){if(index == digits.length()){res.add(str.toString());return;}// 将index只想的数字转为intint digit = digits.charAt(index) - '0';// 取数字对应的字符集String letters = Sites.get(String.valueOf(digit));for(int i = 0; i < letters.length(); i++){str.append(letters.charAt(i));backtracking(digits,index + 1);str.deleteCharAt(str.length() - 1);}}
}