#240. 受限子集和问题
受限子集和问题
Constrained Subset Sum
Background
Congcong is solving an interesting number puzzle. He is given a set of integers and a target sum, and needs to select some numbers from this set such that their sum equals the target sum. However, this puzzle has a special rule that makes Congcong a bit confused.
Problem Description
Given an array of integers nums and a target integer target, determine if it's possible to choose a group of some of the integers from nums such that the group sums to the given target.
Additionally, there is an extra constraint: if there are numbers in the array that are adjacent and have identical values, they must either all be chosen, or none of them chosen.
For example, with the array [1, 2, 2, 2, 5, 2], the three 2's in the middle must either all be chosen or not, all as a group. (One loop can be used to find the extent of the identical values.)
Input Format
The input is given from standard input in the following format. It starts with an integer start (typically 0, indicating to process from the starting index of the array, but in this problem, it might just be a placeholder or used for the starting index of recursion), followed by an array of integers nums, and finally an integer target.
start[num1 num2 ... numN]target
Output Format
Output true if such a subset exists; otherwise, output false.
boolean
Sample
0 [2 4 8] 10
true
0 [1 2 4 8 1] 14
true
0 [2 4 4 8] 14
false
Sample Explanation
- Sample 1: Array
[2, 4, 8], target sum10. Choosing2and8gives a sum of10. The condition is met, outputtrue. - Sample 2: Array
[1, 2, 4, 8, 1], target sum14. Choosing2,4, and8gives a sum of14. The condition is met, outputtrue. - Sample 3: Array
[2, 4, 4, 8], target sum14.- If the two
4s are chosen, the current sum is8. We need14 - 8 = 6. It's not possible to get6from the remaining[2, 8]. - If the two
4s are not chosen, the current sum is0. We need14. It's not possible to get14from the remaining[2, 8](only2,8,10are possible sums). - Therefore, no such subset can be found, output
false.
- If the two
Constraints
Time limit: 1 second, Memory limit: 1024 KiB for each test case.