java - 从 java 中的 alpha 集 {A,B} 生成所有长度为 3 的序列

标签 java permutation sequences

我有以下任务。

输入:{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/

相关文章:

java - 删除 tomcat 7 上的设置默认链接

java - 函数返回结果集,进入另一个类-JAVA

python - 有没有一种实用的方法可以做到这一点?

python - 理解展平一系列序列?

java - 将 JFrame.getText() 从一个类成员传递给另一个类成员?

java - GWT Locale 在地址栏中有效,但在元中无效

python - 有效地生成所有排列

c++ - 是否有类似 next_permutation 的函数,但用于重复排列?

c# - 当角色可以组合到其他角色时,如何从列表中获取所有角色组合

arrays - 在数组中查找重复连续值的最短方法