- //User function template for C++
- bool solve(vector<int>&arr,int sum,vector<int>&dp,int n){
- if(dp[sum]==1){
- return true;
- }
- if(dp[sum]=-1){
- return false;
- }
- if(sum==0){
- dp[sum]=1;
- return true;
- }
- else if(n==0){
- return false;
- }
- else if(sum<0){
- dp[sum]=-1;
- return false;
- }
- bool take= solve(arr,sum-arr[n],dp,n-1);
- bool not_take=solve(arr,sum,dp,n-1);
- if(take==true||not_take==true){
- dp[sum]=1;
- return true;
- }
- dp[sum]=-1;
- return false;
- }
- class Solution{
- public:
- bool isSubsetSum(vector<int>arr, int sum){
- vector<int>dp(sum+1,-2);
- int n=arr.size()-1;
- return solve(arr,sum,dp,n);
- }
- };
- //{ Driver Code Starts.
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int N, sum;
- cin >> N;
- vector<int> arr(N);
- for(int i = 0; i < N; i++){
- cin >> arr[i];
- }
- cin >> sum;
- Solution ob;
- cout << ob.isSubsetSum(arr, sum) << endl;
- }
- return 0;
- }
- // } Driver Code Ends
[text] priyanshu
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Editor
You can edit this paste and save as new: