-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
33 lines (26 loc) · 752 Bytes
/
Copy pathsolution.cpp
File metadata and controls
33 lines (26 loc) · 752 Bytes
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
class Solution {
public:
int totalWays(vector<int>& arr, int target) {
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// If target is impossible to achieve
if (abs(target) > totalSum) {
return 0;
}
// totalSum + target must be even
if ((totalSum + target) % 2 != 0) {
return 0;
}
int required = (totalSum + target) / 2;
vector<int> dp(required + 1, 0);
dp[0] = 1;
for (int num : arr) {
for (int sum = required; sum >= num; sum--) {
dp[sum] += dp[sum - num];
}
}
return dp[required];
}
};