1

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 clarification.

3
  • 1
    If this is a homework assignment, please include the homework tag. Commented Sep 26, 2011 at 23:04
  • The if statement seems redundant. The same check is already present in the for loop condition. Commented Sep 26, 2011 at 23:15
  • It's better to create a new question instead of changing an existing question that has already been answered. Commented Sep 26, 2011 at 23:59

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0
    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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.