Recursion Number of decompositions

Each number can be broken down into parts, or addends. For example, number 3 may be broken down into such addends as 1 + 1 + 1, 2 + 1, 3. This procedure is known as decomposition.
In this task, you'll need to find out all decompositions of number NN (1 \leq N \leq 401≤N≤40) and list its positive addends. The decomposition should be printed in lexicographical order. For example:

1 1 1 1 1
2 2 1
3 1 1
...
Each decomposition should consist of the addends in a non-ascending order, where each subsequent number of the list is equal or less than the previous one.

Note, that inversion of addends doesn't count and 2 + 1 and 1 + 2 are the same operations.
0 is not a positive number.
Sample Input 1:

5
Sample Output 1:

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

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int toDecompose = scanner.nextInt();

        provideDecomposition(toDecompose, toDecompose, "");
    }

    private static void provideDecomposition(int toDecompose, int max, String out) {
        if (toDecompose == 0) {
            System.out.println(out);
        } else if (toDecompose > 0) {
            for (int i = 1; i <= max; i++) {
                provideDecomposition(toDecompose - i, i, out + i + " ");
            }
        }
    }
}
posted @ 2020-08-12 13:13  longlong6296  阅读(161)  评论(0)    收藏  举报