穷举vs暴搜vs深搜vs回溯vs剪枝系列一>电话号码的字母组合
题目:
解析:
代码:
private String[] hash = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; private StringBuffer path; private List<String> ret; public List<String> letterCombinations(String digits) { ret = new ArrayList<>(); path = new StringBuffer(); if(digits.length() == 0) return ret; dfs(digits,0); return ret; } private void dfs(String digits,int pos){ if(digits.length() == pos){ ret.add(path.toString()); return; } char[] cur = hash[digits.charAt(pos)-'0'].toCharArray(); for(int i = 0; i < cur.length; i++){ path.append(cur[i]); dfs(digits, pos+1); //恢复现场 //deleteCharAt (int指数) 移除此序列中指定位置的字符 path.deleteCharAt(path.length()-1); } }