-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTargetSumAssignSignLecture21.cpp
More file actions
38 lines (37 loc) · 942 Bytes
/
Copy pathTargetSumAssignSignLecture21.cpp
File metadata and controls
38 lines (37 loc) · 942 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
34
35
36
37
38
#include <vector>
#include <iostream>
using namespace std;
int numberOfSubsets(vector<int> &num, int tar)
{
int n = num.size();
vector<int> prev(tar+1,0),cur(tar+1);
if(num[0] == 0) prev[0] = 2;
else prev[0] = 1;
if(num[0] <= tar && num[0] != 0) prev[num[0]] = 1;
for(int ind = 1;ind<n;ind++)
{
for(int sum = 0;sum <= tar;sum++)
{
int notTake = prev[sum];
int take = 0;
if(num[ind] <= sum) take = prev[sum - num[ind]];
cur[sum] = (take + notTake);
}
prev = cur;
}
return prev[tar];
}
int countPartitions(int n, int d, vector<int> &arr)
{
int totalSum = 0;
for(auto i : arr)
{
totalSum += i;
}
if((totalSum - d < 0) || (totalSum - d)%2) return 0;
return numberOfSubsets(arr,(totalSum-d)/2);
}
int targetSum(int n, int target, vector<int>& arr)
{
return countPartitions(n,target,arr);
}