我有一個關於計算所有可能的組合的問題。例如,如果我有一個遞歸方法,給我輸出: a。 b 0 0 b。 0 1 c。 1 0 d。 1 1Java - 遞歸 - 計數所有組合
在這種情況下,我有8個可能的輸出。我應該如何使用java來計算它們? 我試圖使用一個計數器,但它給我4.
請幫助。 謝謝。 這是我的代碼。
public static void printAllAssignments(char set[], int k) {
int n = set.length;
printAllAssignments(set, "", n, k);
}
// The main recursive method to print all possible strings of length k
public static void printAllAssignments(char set[], String prefix, int n, int k) {
// Base case: k is 0, print prefix
if (k == 0) {
counterTotalAssignments++;
System.out.println("Occupancies: " + prefix);
return;
}
// One by one add all characters from set and recursively
// call for k equals to k-1
for (int i = 0; i < n; ++i) {
// Next character of input added
String newPrefix = prefix + set[i];
// k is decreased, because we have added a new character
printAllAssignments(set, newPrefix, n, k - 1);
}
}
public static void main(String[] args) {
char charSet[] = {'0', '1'};
int k = 2;
printAllAssignments(charSet, k);
System.out.println("Total number of assignments: " + counterTotalAssignments);
}
output:
Occupancies: 00
Occupancies: 01
Occupancies: 10
Occupancies: 11
Total number of assignments: 4
exp(n,k)?!爲什麼要算你什麼時候可以變得更聰明? –