Subset Sum Problem | Practice | GeeksforGeeks

Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. 

Example 1:
Input:
N = 6
arr[] = {3, 34, 4, 12, 5, 2}
sum = 9
Output: 1 
Explanation: Here there exists a subset with
sum = 9, 4+3+2 = 9.

Example 2:
Input:
N = 6
arr[] = {3, 34, 4, 12, 5, 2}
sum = 30
Output: 0 
Explanation: There is no subset with sum 30.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function isSubsetSum() which takes the array arr[], its size N and an integer sum as input parameters and returns boolean value true if there exists a subset with given sum and false otherwise.
The driver code itself prints 1, if returned value is true and prints 0 if returned value is false.
 
Expected Time Complexity: O(sum*N)
Expected Auxiliary Space: O(sum*N)
 
Constraints:
1 <= N <= 100
1<= arr[i] <= 100
1<= sum <= 105
0
pythonize1 day ago
def recur(dp, arr, S, si):   if S==0: dp[S][si]=1; return 1   if dp[S][si] != -1: return dp[S][si]      ans = 0   if S >= arr[si]:        ans = recur(dp, arr, S-arr[si], si+1)   if ans == 0:       ans = recur(dp, arr, S, si+1)   dp[S][si] = ans   return ans
class Solution:   def isSubsetSum (self, N, arr, S):       dp = [ [-1] * N + [0] for _ in range(S+1) ]       ans = recur( dp, arr, S, 0 )       return ans
+1
sharmaadarsh8593 days ago
//using top down approach class Solution{   public:   bool isSubsetSum(vector<int>arr, int sum){       // code here         int t[arr.size()+2][sum+2];       for(int i=0;i<=arr.size();i++){           for(int j=0;j<=sum;j++){                   if(j==0){                       t[i][j]=1;                   }                   else if(i==0)                       t[i][j]=0;              }       }       for(int i=1;i<=arr.size();i++){           for(int j=1;j<=sum;j++){               if(arr[i-1]<=j){                   // t[i][j]=7;                   t[i][j]=t[i-1][j-arr[i-1]]+t[i-1][j];               }               else if(arr[i-1]>j){                       t[i][j]=t[i-1][j];               }           }       }       return t[arr.size()][sum];   }};
+1
shakeher3 days ago
//recursion
class Solution{
private:
bool solve(vector<int>arr, int sum,int idx){
    
    if(sum == 0)
        return true;
        
    if(idx == 0)
        return (arr[idx] == sum);
        
    bool taken = false;
    if(sum>=arr[idx])
        taken = solve(arr,sum-arr[idx],idx-1);
    
    bool notTaken = solve(arr,sum,idx-1);
    return taken || notTaken;
    
}
public:
    bool isSubsetSum(vector<int>arr, int sum){
        
        return solve(arr,sum,arr.size()-1);
    }
};

//memoization
class Solution{
private:
bool solve(vector<int>arr, int sum,int idx,vector<vector<int>> &dp){
    
    if(sum == 0)
        return true;
        
    if(idx == 0)
        return (arr[idx] == sum);
    
    if(dp[idx][sum]!=-1)
        return dp[idx][sum];
        
    bool taken = false;
    if(sum>=arr[idx])
        taken = solve(arr,sum-arr[idx],idx-1,dp);
    
    bool notTaken = solve(arr,sum,idx-1,dp);
    return dp[idx][sum] = taken || notTaken;
    
}
public:
    bool isSubsetSum(vector<int>arr, int sum){
        int n = arr.size();
        int m = sum+1;
        vector<vector<int>> dp(n,vector<int>(m,-1));
        return solve(arr,sum,arr.size()-1,dp);
    }
};

//tabulation
class Solution{   
public:
    bool isSubsetSum(vector<int>arr, int target){
        int n = (int)arr.size()+1;
        int m = target+1;
        vector<vector<bool>> dp(n,vector<bool>(m,false));
        
        for(int i=0;i<n;i++){
            dp[i][0] = true;
        }
        for(int i=1;i<m;i++){
            dp[0][i] = false;
        }
        
        for(int idx=1;idx<n;idx++){
            for(int sum=1;sum<m;sum++){
                dp[idx][sum] = (arr[idx-1]<=sum)?(dp[idx-1][sum-arr[idx-1]] || dp[idx-1][sum]):(dp[idx-1][sum]);
            }
        }
        
        return dp[n-1][m-1];
    }
};
+1
khimanidhaval3 days ago
int solve(vector<int>arr, int sum, int n, vector<vector<int>>&dp)   {       if(n==0)       {           if(sum==0)           {               return 1;           }                      return 0;       }       if(sum==0)       {           return 1;       }       if(dp[n][sum]!=-1)       {           return dp[n][sum];       }       bool ra=0;       bool la;       if(sum>=arr[n-1])       {  la=solve(arr, sum-arr[n-1],n-1,dp) || solve(arr,sum,n-1,dp);         dp[n][sum]=la;       }       else{          ra=solve(arr,sum,n-1,dp);          dp[n][sum]=ra;       }        return (la||ra);     }
   bool isSubsetSum(vector<int>arr, int sum){       // code here       vector<vector<int>>dp(arr.size()+1, vector<int>(sum+1,-1));       return solve(arr,sum,arr.size(),dp);   }
0
thiruvazhidhinesh3 days ago
JAVA SOLUTION:
class Solution{   static Boolean isSubsetSum(int N, int arr[], int sum){       int[][] dp=new int[N+1][sum+1];       Arrays.sort(arr);       for(int i=1;i<sum+1;i++){           dp[0][i]=0;       }       for(int i=0;i<N+1;i++){           dp[i][0]=0;       }       for(int i=1;i<N+1;i++){           for(int j=1;j<sum+1;j++){               if(j<arr[i-1]){                   dp[i][j]=dp[i-1][j];               }               else{                   dp[i][j]=Math.max(dp[i-1][j],arr[i-1]+dp[i-1][j-arr[i-1]]);               }           }       }       if(dp[N][sum]==sum) return true;       return false;   }}
0
anonymous15074 days ago
int n = arr.size();       int dp[n+1][sum+1];       //initialisation       for(int i =0;i<n+1;i++)       {           for(int j =0;j<sum+1;j++)             {                 if(i==0)                   dp[i][j]= false;                 if(j==0)                   dp[i][j] = true;             }       }              for(int i=1;i<n+1;i++)       {           for(int j =1;j<sum+1;j++)           {               if(arr[i-1]<=j)               dp[i][j]=dp[i-1][j-arr[i-1]] || dp[i-1][j];               else                 dp[i][j]=dp[i-1][j];           }       }       return dp[n][sum];   }
0
kadamavp4 days ago
Why does this fail for few testcases?
// { Driver Code Starts
//Initial template for C++

#include<bits/stdc++.h> 
using namespace std; 

 // } Driver Code Ends
//User function template for C++

class Solution{   
public:
    bool helper(vector<int>arr, int n ,int sum){
        
        
        bool t[n+1][sum+1];
        
        
        //INITIAILIZATION
        for(int i =0; i<n+1; i++){
            for(int j = 0; j<sum+1; j++){
                if( i==0 ){
                    t[i][j] = false;
                }
                if(j == 0){
                    t[i][j] = true;
                }
            }
        }
        
        for(int i=1; i<n+1; i++){
            for(int j = 1; j<sum+1; j++){
                if(arr[i-1] <= j){
                    t[i][j] = (t[i-1][j-arr[i-1]] || t[i-1][j]);
                }
                else{
                    t[i][j] = t[i-1][j];
                }
                
            }
        }
        
        return t[n][sum];
    }
    bool isSubsetSum(vector<int>arr, int sum){
        // code here 
        int n = arr.size()-1;
        return helper(arr,n,sum);
        
    }
};

// { 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
+1
nikhilchakravarthy094 days ago
class Solution{   
public:
    bool isSubsetSum(vector<int>arr, int sum){
        // code here 
        int n=arr.size();
        vector<vector<bool>> dp(n,vector<bool>(sum+1,0));
        for(int i=0;i<n;i++)
            dp[i][0] = true;
        dp[0][arr[0]] = true;
        for(int i=1;i<n;i++){
            for(int target=1;target<=sum;target++){
                bool notake = dp[i-1][target];
                bool take = false;
                if(target >= arr[i]){
                    take = dp[i-1][target-arr[i]];
                }
                dp[i][target] = (take | notake);
            }
        }
        return dp[n-1][sum];
    }
};
0
sumanthbolle3125 days ago
bool isSubsetSum(vector<int>arr, int sum){
        sort(arr.begin(),arr.end());
        int n =arr.size();
        int temp = arr[0];
        for(int i=1;sum>arr[i];i++)
        {
            if(arr[i] == sum || temp == sum)
               return 1;
            else if(temp < sum)
             temp += arr[i];
        }
        return temp == sum;
        // code here 
        
    }
 
Code does pass 32 test cases out of 34, any ideas to improve it?
0
armaanbgp5 days ago
Working:
vector<vector<int>> dp(arr.size(),vector<int>(sum+1,-1));
Not Working:
vector<vector<bool>> dp(arr.size(),vector<bool>(sum+1,-1));
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.