开发者

Finding by Recursion Sequences of Characters in a Char Array

开发者 https://www.devze.com 2023-04-08 09:14 出处:网络
I have a recursion project to find all the sequences(or subsets) of a Char array as such that each character appears in the same order.For Example, for the array Char[] letters = {\'A\', \'B\',\'C\',\

I have a recursion project to find all the sequences(or subsets) of a Char array as such that each character appears in the same order. For Example, for the array Char[] letters = {'A', 'B','C','D'}

The one letter sequences are "A","B","C,"D".
Two letter sequences are "AB","AC","AD","BC","BD","CD".

Three letter sequences are "ABC", "ABD","ACD","BCD"

Four letter sequence is "ABCD"

Now I thought I was on the right track with the code below, but I'm getting a lot of duplicates. I'm getting really frustrated. If anyone can point me in the right direction, I would appreciate it.

// 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);
                }
            }

    }

Editting out my edit for clarificati开发者_如何学编程on.


You seem to have used the wrong variable here:

combinations(prefix + array[i], array, index+1);

It should be i instead of index:

combinations(prefix + array[i], array, i+1);

Output:

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

Ideone: http://ideone.com/H4Okw


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

The result is:

A
AB
ABC
AC
B
BC
C
0

精彩评论

暂无评论...
验证码 换一张
取 消