递归中字符串数组的排列

时间:2014-09-11 08:24:10

标签: java recursion permutation

String[] test = { "la", "li", "lo" };
language(3, test);

private String language(int n, String[] syllables) { // example of N = 3
    for (int i = 0; i < syllables.length; i++) {
        String w1 = syllables[i];
        for (int j = 0; j < syllables.length; j++) {
            String w2 = syllables[j];
            for (int x = 0; x < syllables.length; x++) {
                String w3 = syllables[x];
                System.out.println(w1 + w2 + w3);
            }
        }
    }
}

我试图创建一个可以创建任何形式的String数组的递归方法。 但我无法实现这一目标

变量

n = amount of syllables  
syllables = String Array of the base words 

输出

lalala
lalali
lalalo
lalila
lalili
lalolo
lilala
lolala
lilili
lololo
......

2 个答案:

答案 0 :(得分:3)

这将为您提供您期望的结果:

String[] test = { "la", "li", "lo" };
language(3, test, "");

private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
    if (n == 0) {
        System.out.println(currentWord);
    } else {
        for (int i = 0; i < syllables.length; i++) {
            language(n - 1, syllables, currentWord + syllables[i]);
        }
    }
}

答案 1 :(得分:2)

你需要这些内容:

private void recursiveMethod(int numberOfSyllablesToAdd, String[] syllables, String word) {
    for (int i = 0; i < syllables.length; i++) {
        String newWord = word + syllables[i];
        if (numberOfSyllablesToAdd >= 0) {
            recursiveMethod(numberOfSyllablesToAdd - 1, syllables, newWord);
       } else {
            System.out.println(newWord);
        }
    }
}

注意:由于多种原因(例如没有使用StringBuilder或StringBuffer来创建单词),这实际上是无效的。