Combination Sum
Practice this coding question on Coding Gurukul.
Problem statement
A packaging desk offers reusable box sizes. An order must be packed to an exact total capacity, and the desk has an unlimited supply of every listed size. The planner needs all different size combinations that meet the order, without treating a different packing order as a new solution. Your task Given distinct positive candidate sizes and a positive target, list every combination whose sum is exactly the target. Any size may be used repeatedly. Sort each combination increasingly and output combinations in numeric lexicographic order, comparing integer values and placing a shorter prefix first. Print the number of combinations before the rows. If no combination works, print 0 only. Never include an oversized or partial combination. Different counts of a size create different combinations; rearranging the same sizes does not. Worked example For sizes [3, 4, 8] and target 12, the combinations are 3 3 3 3, 4 4 4, and 4 8. Print count 3 followed by those rows. The order 8 4 describes the same packing as 4 8 and is not printed again.
Input format
First line: n target. Second line: n distinct candidate sizes.
Output format
Print the combination count followed by its sorted combinations, one per line, in numeric lexicographic order.
Constraints
1 <= n <= 30; 2 <= candidate <= 40; 1 <= target <= 40; fewer than 150 valid combinations.
Sample input
3 12 3 4 8
Sample output
3 3 3 3 3 4 4 4 4 8
Sign in to run or submit a solution in C++, Java or Python.