-2

I have the following code from Print all unique integer partitions given an integer as input

void printPartitions(int target, int maxValue, String suffix) {
    if (target == 0)
        System.out.println(suffix);
    else {
        if (maxValue > 1)
            printPartitions(target, maxValue-1, suffix);
        if (maxValue <= target)
            printPartitions(target-maxValue, maxValue, maxValue + " " + suffix);
    }
}

When it calls printPartitions(4, 4, ""); it gives the below output:

1 1 1 1 
1 1 2 
2 2 
1 3 
4 

How can I get the output in an array like this:

[[1,1,1,1],[1,1,2],[2,2],[1,3],[4]]

1 Answer 1

0

You should collect your values to an array in this case. I've replaced the array with a list, for simplification of "add" operation (for an array you should maintain also indexes):

void printPartitions(int target, int maxValue, List<String> suffix, List<List<String>> list) {
    if (target == 0) {
        list.add(suffix);
    } else {
        if (maxValue > 1)
            printPartitions(target, maxValue-1, suffix, list);
        if (maxValue <= target) {
            List<String> tmp = new ArrayList<String>();
            tmp.add(0, String.valueOf(maxValue));
            tmp.addAll(suffix);
            printPartitions(target-maxValue, maxValue, tmp, list);
        }
    }
}

void callPrintPartitions() {
    List<List<String>> list = new ArrayList<List<String>>();
    printPartitions(4, 4, new ArrayList<String>(), list);
    System.out.println(list);
}

Output:

[[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]]
Sign up to request clarification or add additional context in comments.

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.