Java 打印给定长度的所有可能字符串

Java 打印给定长度的所有可能字符串,java,Java,给定一个字母串和一个数字k,编写一个函数来打印这些字母长度k的所有组合 该字符串不包含重复的字母 输入:{'a','b','d','s','e'} 预期产出:abd、abs、abe、ads、ade、bds、bde、bse、dse 我在使用递归 基本情况是当intk为0时,返回前缀 如果不满足基本大小写,则逐步添加字符数组中的所有字符,并递归调用k=k-1 // Recursive method used to print all possible strings of length k, giv

给定一个字母串和一个数字k,编写一个函数来打印这些字母长度k的所有组合

该字符串不包含重复的字母

输入
{'a','b','d','s','e'}

预期产出
abd、abs、abe、ads、ade、bds、bde、bse、dse

我在使用递归

基本情况是当int
k
为0时,返回前缀

如果不满足基本大小写,则逐步添加字符数组中的所有字符,并递归调用
k=k-1

// Recursive method used to print all possible strings of length k, given a set of characters.
private static void printAllCombinations(char[] alphabet, String prefix, int n, int k) {
    // Base case: k is 0,
    // print prefix.
    if (k == 0) {
        System.out.print(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 + alphabet[i];

        // k is decreased, because
        // we have added a new character.
        printAllCombinations(alphabet, newPrefix, n, k - 1);
    }
}
//在给定一组字符的情况下,用于打印长度为k的所有可能字符串的递归方法。
私有静态void printAllCombinations(字符[]字母,字符串前缀,int n,int k){
//基本情况:k为0,
//打印前缀。
如果(k==0){
系统输出打印(前缀+“”);
返回;
}
//逐个添加所有字符
//从集合递归地
//要求k等于k-1。
对于(int i=0;i
实际产出
aaa aab aad aae abb abd abd abd abd abd abd abd abd abd abd abd abd adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adb adbsad sas sae sba sbb sbd sbe sda sdb sdd sds sde ssa ssb ssd sss sse sea sea seb sed ses见eaa eab eas eae eba ebb ebd ebs ebe eda edb edd eds esa esd ese ese eea eeb eed eee

我可以采取哪些不同的措施来实现所需的输出


我知道我的函数,
printAllCombinations
实际工作正常。我只是不明白如何才能实现所需的输出。

您可以使用
n
来跟踪您在数组
字母表中的当前位置

public static void printAllCombinations(char[] alphabet, int k) {
    printAllCombinations(alphabet, "", 0, k);
}
private static void printAllCombinations(char[] alphabet, String prefix, int n, int k) {
    if (k == 0) { //base case unchanged
        System.out.print(prefix + " ");
        return;
    }
    for (int i = n; i < alphabet.length; i++) { //loop only from n to end of array
        String newPrefix = prefix + alphabet[i];

        printAllCombinations(alphabet, newPrefix, i + 1, k - 1);
    }
}

它将输出:
abd、abs、abe、ads、ade、ase、bds、bde、bse、dse

如何解释和实现“字符串不包含重复字母表”的规则。许多字符串包含重复的字母。
if (k == 0) {
    if (n > prefix.length()) {
        System.out.print(", ");
    }
    System.out.print(prefix);
    return;
}