通过Char数组中字符的递归序列查找

Pen*_*enn 1 java recursion

我有一个递归项目来查找Char数组的所有序列(或子集),使得每个字符以相同的顺序出现.例如,对于数组Char [] letters = {'A', 'B','C','D'}
单字母序列是"A","B","C,"D".
两个字母序列是"AB","AC","AD","BC" "BD", "CD".
三个字母序列是"ABC", "ABD", "ACD", "BCD"
4个字母的顺序是"ABCD"

现在我认为我的代码如下,但是我得到了很多重复.我真的很沮丧.如果有人能指出我正确的方向,我将不胜感激.

// print all subsets of the characters in s
    public static void combinations(char[] array) { combinations("", array, 0); }

    // print all subsets of the remaining elements, with given prefix 
    private static void combinations(String prefix, char[] array, int index) {

        for(int i = index; i < array.length; i++)
        {

            System.out.println(prefix + array[i]);
        }


            if (index < array.length) { 
                for(int i = index; i < array.length; i++){
                    combinations(prefix + array[i], array, index+1);
                }
            }

    }
Run Code Online (Sandbox Code Playgroud)

编辑我的编辑以澄清.

Mar*_*ers 5

你似乎在这里使用了错误的变量:

combinations(prefix + array[i], array, index+1);
Run Code Online (Sandbox Code Playgroud)

它应该是i代替index:

combinations(prefix + array[i], array, i+1);
Run Code Online (Sandbox Code Playgroud)

输出:

A
B
C
D
AB
AC
AD
ABC
ABD
ABCD
ACD
BC
BD
BCD
CD

Ideone:http://ideone.com/H4Okw