回溯算法是不是很是陌生啊,我敢开始也是一脸你蒙蔽,后来我终于忍不住了,就去查查什么是回溯,原来是这个情况,回溯和递归有点类似,但是又不是递归,比如我现在计算数据从0开始到2,当到达状态值2我就回溯,我从1开始回溯,我在回到0,就是for循环我不按套路从小到打,去输出了,我采用回溯,
public class Main { public static void main(String[] args) { List<String> stringList = begin("23"); System.out.println(stringList.toString()); } // 定义每个数字对应的字符 static String[] a = new String[] {"","","abc","def", "ghi","jkl","mno","pqrs","tuv","wxyz"}; // 这个是输出的字符串 static StringBuffer sb = new StringBuffer(); private static List<String> begin(String str) { if (str.length() == 0) { return null; } List<String> result = new ArrayList<>(15); zihe(str,0,result); return result; } private static void zihe(String str, int n, List<String> result) { if (n == str.length()) { result.add(sb.toString()); return; } for (int i = 0; i < a[str.charAt(n)-'0'].length(); i++) { sb.append(a[str.charAt(n)-'0'].charAt(i)); zihe(str, n + 1, result); sb.deleteCharAt(sb.length() - 1); } } }