我試圖找到一些關於如何在Java中查找給定組(可能是字符串或整數數組)的所有組合的示例。我也碰到這個代碼塊來(在http://introcs.cs.princeton.edu/java/23recursion/Combinations.java.html發現我在這裏只複製相關的部分。):在Java中查找組合的遞歸算法
// print all subsets of the characters in s
public static void comb1(String s) { comb1("", s); }
// print all subsets of the remaining elements, with given prefix
private static void comb1(String prefix, String s) {
if (s.length() > 0) {
System.out.println(prefix + s.charAt(0));
comb1(prefix + s.charAt(0), s.substring(1));
comb1(prefix, s.substring(1));
}
}
// read in N from command line, and print all subsets among N elements
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0, N);
// using first implementation
comb1(elements);
System.out.println();
}
不過,我真不明白它是如何工作的。有人關心解釋嗎?
是不是你有問題的代碼,還是它的基本原則?你可能想要拿一支鉛筆和紙,然後穿過一小塊樣本。從N = 2開始,並遵循代碼用「abc」所做的事情。 – Bart