-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDP Target sum
More file actions
41 lines (39 loc) · 1.15 KB
/
Copy pathDP Target sum
File metadata and controls
41 lines (39 loc) · 1.15 KB
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
This questions breaks upto the one in which we have two subarrays
with a difference d , in this question the given target is the difference
if there exists that difference then we have to return the t
class Solution {
public:
int func(int ind ,int s1,vector<vector<int>>&dp,vector<int>&arr){
// if(s1==0){
// return 1;
// }
if(ind==0){
if(s1==0&&arr[0]==0)return 2;
if(s1==0||s1==arr[0])return 1;
return 0;
}
if(dp[ind][s1]!=-1){
return dp[ind][s1];
}
int nottake = func(ind-1,s1,dp,arr);
int take = 0;
if(s1>=arr[ind]){
take = func(ind-1,s1-arr[ind],dp,arr);
}
return dp[ind][s1]=take+nottake;
}
int findTargetSumWays(vector<int> &nums,int target) {
int n = nums.size();
// Write your code here.
int totalsum = 0;
for(int i =0;i<nums.size();i++){
totalsum+=nums[i];
}
int s1 = (totalsum-target)/2;
if ((totalsum - target) % 2 == 0 && totalsum - target >= 0) {
vector<vector<int>> dp(n, vector<int>(s1 + 1, -1));
return func(n - 1, s1, dp, nums);
}
return 0;
}
};