本文主要是介绍代码随想录——电话号码的字母组合(Leetcode17),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接
回溯
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);}}
}
这篇关于代码随想录——电话号码的字母组合(Leetcode17)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!