#239. 带约束的组合求和
带约束的组合求和
Group Sum with Special Constraints
Background
Congcong has been studying how to select specific combinations from a set of numbers. He encountered an interesting problem that requires your help to solve.
Problem Description
Given an array of integers and a target sum , determine if it's possible to choose a group of some of the integers from the array such that their sum equals , with these additional constraints:
- All multiples of in the array must be included in the group.
- If the value immediately following a multiple of is , it must not be chosen. (No loops needed.)
Input Format
The input consists of a single line. This line contains an integer , a list of integers enclosed in square brackets, and an integer . In this problem, will always be .
start_index [num1 num2 ... numK] target
Output Format
Output to standard output in the following format.
Output
trueif such a group exists; otherwise, outputfalse.
Sample
0 [2 5 10 4] 19
true
0 [2 5 10 4] 17
true
0 [2 5 10 4] 12
false
Sample Explanation
Sample 1: For input 0 [2 5 10 4] 19, the multiples of in the array are and , which must be included. Their sum is . The target sum is , so more is needed. Choosing from the remaining elements achieves the target. The chosen group is , with a sum of . Thus, true is output.
Sample 2: For input 0 [2 5 10 4] 17, the multiples of in the array are and , which must be included. Their sum is . The target sum is , so more is needed. Choosing from the remaining elements achieves the target. The chosen group is , with a sum of . Thus, true is output.
Sample 3: For input 0 [2 5 10 4] 12, the multiples of in the array are and , which must be included. Their sum is . Since is already greater than the target sum , it's impossible to reach the target by adding non-negative numbers. Thus, false is output.
Constraints
Time limit: second, Memory limit: KiB for each test case.