Distinct Combination Sum

medium backtracking sorting arrays 2000 ms · 256 MB

Distinct Combination Sum

Dale's hardware store has n washers in a bin. The i-th washer weighs w_i grams; several washers can share the same weight. A customer wants to glue together a stack of washers whose total weight is exactly T grams, using each physical washer at most once.

Two stacks are considered the same if they consist of the same weights with the same multiplicities (which physical washer was picked doesn't matter) — so if the bin has two washers of weight 5 and the customer only needs one of them, using the first or the second gives the same stack.

List every distinct stack that weighs exactly T grams. Within a stack, print the weights in non-decreasing order. Order the stacks themselves in lexicographic order: compare them weight by weight from the first position, and if one stack is a prefix of another, the shorter one comes first.

It is guaranteed that there are at most 10^4 distinct stacks.

Input

The first line contains two integers n and T (1 ≤ n ≤ 30, 1 ≤ T ≤ 60).

The second line contains n integers w_1, …, w_n (1 ≤ w_i ≤ 60) — the weights of the washers in the bin.

Output

Print an integer m — the number of distinct stacks that weigh exactly T grams.

Then print m lines, each describing one stack in the order defined above: the weights of its washers, in non-decreasing order, separated by single spaces.

If no stack weighs exactly T grams, print 0 and nothing else.

Notes

In the first example the washers are [10, 1, 2, 7, 6, 1, 5] and the target is 8. The stacks that sum to 8 are [1, 1, 6], [1, 2, 5], [1, 7] and [2, 6], listed in lexicographic order.

Example 1

Input

7 8
10 1 2 7 6 1 5

Output

4
1 1 6
1 2 5
1 7
2 6

Example 2

Input

3 10
5 5 5

Output

1
5 5

Hints · reveal one at a time if you're stuck

Hint 1

Washers with the same weight are interchangeable, so two searches that pick different physical washers of one weight give the same stack. Sort the weights, and think of the stack as a multiset of weights, so that each distinct weight is chosen as a count.

Hint 2

Build stacks by depth-first search, choosing weights in non-decreasing order and only ever moving forward past a weight value once you are done with it. Stop extending a branch as soon as the next weight would exceed what remains, since the weights are sorted.

Hint 3

Make sure each distinct weight value is tried as a whole block of choices at each level, respecting how many washers of that weight exist. Visiting branches in increasing weight order produces the stacks already in the required lexicographic order.

report an issue Prefer your own editor? sooks prep 59 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.