#K82492. Combination Sum
Combination Sum
Combination Sum
Given a list of distinct positive integers called candidates and a target integer T, your task is to find all unique combinations of candidates where the chosen numbers sum up exactly to T. Each number in candidates can be used an unlimited number of times. Two combinations are considered the same if they consist of the same multiset of elements, regardless of the order. The combinations in the output must be sorted in non-decreasing order.
Formally, you are to find all sequences \(a_1, a_2, \ldots, a_k\) such that:
\(a_1 + a_2 + \cdots + a_k = T\) with \(a_1 \le a_2 \le \cdots \le a_k\) and each \(a_i\) is an element from candidates.
It is guaranteed that the number of unique combinations is finite for each test case.
Example 1:
Input: candidates = [2, 3, 6, 7], T = 7
Output: [[2, 2, 3], [7]]
Example 2:
Input: candidates = [2, 3, 5], T = 8
Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
inputFormat
The input is read from stdin
and consists of two lines:
- The first line contains space-separated positive integers representing the candidate numbers.
- The second line contains a single integer representing the target sum T.
It is guaranteed that the list of candidates does not contain duplicates.
outputFormat
The output should be written to stdout
as a single line in the form of a Python-like list of lists. Each inner list represents one valid combination. If there are no valid combinations, output an empty list []
.
2 3 6 7
7
[[2, 2, 3], [7]]