-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec10_41.cpp
65 lines (50 loc) Β· 1.38 KB
/
lec10_41.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
59
60
61
62
63
64
65
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
bool f(int ind , int target , vector<int> &arr,vector<vector<int>>&dp){
if(target == 0 ) return true;
if( ind == 0 ) return ( arr[0] == target);
if(dp[ind][target]!= -1) return dp[ind][target];
bool notTake = f(ind - 1 , target , arr,dp);
bool take = false;
if(arr[ind] <=target) take = f( ind-1 , target-arr[ind],arr,dp);
return dp[ind][target]=take | notTake;
}
bool isSubsetSum(vector<int>& arr, int target) {
// code here
int n = arr.size();
vector<vector<int>>dp( n+1 , vector<int>(target+1 , -1));
return f(n-1 , target , arr,dp);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
int sum;
cin >> sum;
cin.ignore();
Solution ob;
if (ob.isSubsetSum(arr, sum))
cout << "true" << endl;
else
cout << "false" << endl;
cout << "~" << endl;
}
return 0;
}
// } Driver Code Ends