所以我需要这种算法才能工作,但我似乎找不到问题所在。我需要打印[a,b,c,d]的所有可能组合(长度为4),一些条件(已经在算法中)。那我想念什么呢?我仍然是Java的初学者,非常感谢您的帮助!
public class Test {
//Method saying that 'a' always have to follow 'b'
public static boolean aFollowsB(String s) {
char[] set1 = s.toCharArray();
for (int i = 0; i < set1.length; i++) {
// If B is the last char, A can't possilby follow
if (i == set1.length - 1) {
if (set1[i] == 'b') { return false; }
// Else if we encounter B, make sure next is an A
} else {
if (set1[i] == 'b') {
if (set1[i+1] != 'a') { return false; }
}
}
}
return true;
}
//Method saying that we can't have 'a' and 'd' in the same string
public static boolean hasOnlyAOrD(String s) {
char[] set1 = s.toCharArray();
boolean hasA = false;
boolean hasD = false;
for (int i = 0; i < set1.length; i++) {
if (set1[i] == 'a') {
hasA = true;
} else if (set1[i] == 'd') {
hasD = true;
}
}
if (hasA && hasD) {
return false;
}
return true;
}
//Method printAllKLength to print all possible strings of k lenght
static void printAllKLength(char[] set, int k) {
int n = set.length;
printAllKLengthRec(set, "", n, k);
}
static void printAllKLengthRec (char[] set,
String prefix,
int n, int k)
{
if (k == 0) {
System.out.println(prefix);
System.out.println(prefix);
return;
}
for (int i = 0; i < n; ++i) {
String newPrefix = prefix + set[i];
printAllKLengthRec(set, newPrefix,
n, k - 1);
}
}
//Method to print with the conditions
public static void main(String[] args) {
char[] set1 = {'a', 'b', 'c', 'd'};
int k = 4;
if (aFollowsB(set1) && hasOnlyAOrD(prefix)) {
printAllKLength(set1, k);
}
}}
首先,修复printAllKLengthRec:
不要打印所有内容两次,如果前缀已经包含set [i],则停止递归操作
static void printAllKLengthRec(char[] set, String prefix, int n, int k) {
if (k == 0) {
System.out.println(prefix);
return;
}
for (int i = 0; i < n; ++i) {
if (!prefix.contains("" + set[i])) {
String newPrefix = prefix + set[i];
printAllKLengthRec(set, newPrefix, n, k - 1);
}
}
}