我有以下任务。
输入:{A,B} 和 3。
输出:以下所有序列:(A,A,A), (A,A,B), (A,B,A), (A,B,B), (B,A,A), (B,A,B), (B,B,A), (B,B,B).
到目前为止,我能想到的就是使用递归。我们从一个空根节点开始。然后,我们再添加三个级别,每个级别对应于要创建的序列的一个条目。每个节点有两个子节点,一个是A值,一个是B值。那么,从根到叶顶点的每条路径就是我们要找的一个序列。
有没有更有效的方法来做到这一点?
最佳答案
public class Program {
public static void main(String[] args) {
// Create an alphabet to work with
char[] alphabet = new char[] {'a','b'};
// Find all possible combinations of this alphabet in the string size of 3
StringExcersise.possibleStrings(3, alphabet,"");
}
}
class StringExcersise {
public static void possibleStrings(int maxLength, char[] alphabet, String curr) {
// If the current string has reached it's maximum length
if(curr.length() == maxLength) {
System.out.println(curr);
// Else add each letter from the alphabet to new strings and process these new strings again
} else {
for(int i = 0; i < alphabet.length; i++) {
String oldCurr = curr;
curr += alphabet[i];
possibleStrings(maxLength,alphabet,curr);
curr = oldCurr;
}
}
}
}
关于java - 从 java 中的 alpha 集 {A,B} 生成所有长度为 3 的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28016613/