-
Notifications
You must be signed in to change notification settings - Fork 0
/
target_sum.cpp
58 lines (45 loc) · 971 Bytes
/
target_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
int target_sum(vector<int> nums, int i, int target, int sum, char operation) {
if (operation == '+') {
sum += nums[i];
}
else {
sum -= nums[i];
}
if (i == nums.size() - 1) {
if (sum == target) {
return 1;
}
return 0;
}
int ans = 0;
ans += target_sum(nums, i + 1, target, sum, '+');
ans += target_sum(nums, i + 1, target, sum, '-');
return ans;
}
int findTargetSumWays(vector<int> nums, int target) {
return target_sum(nums, 0, target, 0, '+') + target_sum(nums, 0, target, 0, '-');
}
void solve() {
int n, target;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
cin >> target;
cout << target_sum(nums, 0, target, 0, '+') + target_sum(nums, 0, target, 0, '-') << endl;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}