#K56502. Combination Sum II
Combination Sum II
Combination Sum II
You are given a list of integers arr
(which may contain duplicates) and a target integer target
. Your task is to find all unique combinations of elements in arr
where the sum of the numbers is equal to target
. Each element in arr
may be used at most once in each combination. The combinations should be output in lexicographical order.
Note: Two combinations are considered unique if they differ in at least one chosen index. The order within each combination does not matter.
The solution can be understood in terms of backtracking. Formally, if we denote a combination as an array \( c = [c_1, c_2, \dots, c_k] \), then we require
[ \sum_{i=1}^{k} c_i = target, \quad c_i \in arr, \quad \text{each element is used at most once}, ]
and the combinations must be sorted in lexicographical order.
inputFormat
The input is provided via standard input (stdin) and consists of two lines:
- The first line contains space-separated integers representing the array
arr
. - The second line contains a single integer representing the
target
.
outputFormat
Output the list of unique combinations (each combination is a list of integers) that add up to the target. The output should be printed to standard output (stdout) as a Python-style list-of-lists representation.
For example, if the output is a single combination [7], you should print:
[[7]]## sample
2 3 6 7
7
[[7]]