我有一个关于计算所有可能的组合的问题。例如,如果我有一个递归方法,给我输出: 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)?!为什么要算你什么时候可以变得更聪明? –