回溯算法是不是很是陌生啊,我敢開始也是一臉你蒙蔽,後來我終于忍不住了,就去查查什麼是回溯,原來是這個情況,回溯和遞歸有點類似,但是又不是遞歸,比如我現在計算資料從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);
}
}
}