从java中的alpha集合{A,B}生成长度为3的所有序列
我有以下任务 输入:{A,B}和3 输出:以下所有序列:(A,A,A,B),(A,B,A),(A,B,B),(B,A,A),(B,A,B),(B,B,A),(B,B,B,B) 到目前为止,我能想到的是使用递归。我们从一个空根节点开始。然后,我们再添加三个级别,每个级别对应于要创建序列的条目。每个节点有两个子节点,一个有值A,另一个有值B。然后,从根到叶顶点的每条路径都是我们要寻找的序列 还有更有效的方法吗从java中的alpha集合{A,B}生成长度为3的所有序列,java,permutation,sequences,Java,Permutation,Sequences,我有以下任务 输入:{A,B}和3 输出:以下所有序列:(A,A,A,B),(A,B,A),(A,B,B),(B,A,A),(B,A,B),(B,B,A),(B,B,B,B) 到目前为止,我能想到的是使用递归。我们从一个空根节点开始。然后,我们再添加三个级别,每个级别对应于要创建序列的条目。每个节点有两个子节点,一个有值A,另一个有值B。然后,从根到叶顶点的每条路径都是我们要寻找的序列 还有更有效的方法吗 公共类程序{ public class Program { public sta
公共类程序{
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;
}
}
}
}
公共静态void main(字符串[]args){
//创建要使用的字母表
字符[]字母表=新字符[]{'a','b'};
//查找字符串大小为3的此字母表的所有可能组合
StringExcersise.可能的字符串(3,字母,“”);
}
}
课堂练习{
公共静态void-possibleStrings(int-maxLength、char[]字母、字符串curr){
//如果当前字符串已达到其最大长度
if(curr.length()=maxLength){
系统输出打印项次(当前);
//否则,将字母表中的每个字母添加到新字符串中,并再次处理这些新字符串
}否则{
for(int i=0;i
因为它是两个的集合,所以可以认为是二进制的。A=0,B=1,然后用二进制向上计数。@Phil_1984,非常感谢你的评论。你的想法不仅适用于一组两个,对吗?我的意思是,如果这个集合是三个,我们可以考虑另一个基于它的数字系统。我想是一样的。是的,你在这里做的就是用不同的基数计算。是的。如果是A,B,C,你可以用三元数(基数3),000,001,002,010,011,等等