回溯法(算法)
leecode第17题
从上至下遍历每个节点,直至最深深度为方法出口,返回上一层,然后移除当前元素。
public class test { public static void main(String[] args) { String s = "23"; List<String> list = new test().solution(s); System.out.println(list); } private List<String> solution(String digits) { List<String> combinations = new ArrayList<>(); if (digits.length() == 0) { return combinations; } Map<Character, String> phoneMap = new HashMap<Character, 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"); }}; int p = 0; StringBuilder sb = new StringBuilder(); List result = exectorSolution(phoneMap, digits, combinations, p, sb); return result; } private List exectorSolution(Map<Character, String> phoneMap, String digits, List<String> combinations, int p, StringBuilder sb) { //若索引遍历到底后,递归方法结束 if (digits.length() == p) { //达到最深,list中添加sb其中一种组合情况 combinations.add(sb.toString()); } else { String str = phoneMap.get(digits.charAt(p)); //遍历当前深度对应的所有字符 for (int i = 0; i < str.length(); i++) { sb.append(str.charAt(i)); //回溯法,调用下一个节点深度的所有字符 exectorSolution(phoneMap, digits, combinations, p + 1, sb); //结束后把当前的字符串从sb中移除 sb.deleteCharAt(p); } } return combinations; } }