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
+1
avinashdhn19041 day ago
class Solution{   
public:
    bool isSubsetSum(vector<int>arr, int sum){
        int n=arr.size();
        // using Dynamic programming
        // bool t[n+1][sum+1];
        // for(int i=0;i<=n;i++){
        //     for(int j=0;j<=sum;j++){
        //         if(i==0)t[i][j]=0;
        //         if(j==0)t[i][j]=1;
        //     }
        // }
        // for(int i=1;i<=n;i++){
        //     for(int j=1;j<=sum;j++){
        //         if(j>sum)t[i][j]=t[i-1][j];
        //         else t[i][j]=t[i-1][j-arr[i-1]]||t[i-1][j];
        //     }
        // }
        // return t[n][sum];
        
        // using bitset
        bitset<100001>dp(0);
        dp[0]=1;
        for(int i=0;i<n;i++)dp=dp|(dp<<arr[i]);
        return dp[sum];
    }
};
0
vinaykush2 days ago
Simple KnapsSack in 1-D Dp
class Solution{   
public:
bool subset(vector<int>& arr,int currIndex,int lastIndex,int targetSum,vector<int>& dp){
    if(targetSum<0)
    return false;
    if(targetSum==0)
    return true;
    if(currIndex>lastIndex)
    return false;
    if(dp[targetSum]!=-1)
    return dp[targetSum];
    return dp[targetSum]=(subset(arr,currIndex+1,lastIndex,targetSum-arr[currIndex],dp)||subset(arr,currIndex+1,lastIndex,targetSum,dp));
}
    bool isSubsetSum(vector<int>arr, int sum){
        // code here 
        vector<int> dp(sum+5,-1);
        return subset(arr,0,arr.size()-1,sum,dp);
    }
};
+1
adarshgupta4014 days ago
Simple Java DP knapSack Soln
class Solution{
    static Boolean isSubsetSum(int n, int arr[], int sum){
        // Dp- 0-1 Knapsack , Subset Sum
        boolean dp[][] = new boolean[n+1][sum+1];
        for(int i = 0 ; i< sum+1; i++) dp[0][i] = false;  // making 1st row false, no non-zero no can give zero sum
        for(int i = 0 ; i< n+1; i++) dp[i][0] = true;    // making whole 1st column true, null set will always give zero sum for any numbers.
    
        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];
    }
}
+1
aniketsaraswat1122 weeks ago
bool isSubsetSum(vector<int>arr, int sum){
        int n = arr.size();
        bool dp[n+1][sum+1] = {};
        for(int i = 0; i<=n; i++) dp[i][0] = true;
        for(int i = 1; i<= n; i++){
            for(int j = 0; j<=sum; j++){
                if(arr[i-1] == j) dp[i][j] = true;
                else if(j > arr[i-1]) 
                    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
devashishbakare2 weeks ago
JAVA DP
 
static Boolean isSubsetSum(int N, int arr[], int sum){
     
     if(N <= 0 )
     return false;
     
     //created a boolean array for checking in past
     //did we have some for this curret processing subset
     
     //N+1, we have to consider empty array as well
     //sum+1 out column represent a taeger, so its zero base indexing hence we have to add extra one
     boolean dp[][] = new boolean[N+1][sum+1];
     
     int n = dp.length-1;
     int m = dp[0].length-1;
     //outer for loop is travers for the array elemets including 0
     for(int i = 0; i <dp.length; i++)
     {
         //inner for loop ran through target;
         for(int j = 0 ; j < dp[0].length ; j++)
         {
             //if Im stading on emety set and target is zero
             if(i == 0 &&  j == 0)
                dp[i][j] = true;
             //empty set can be part of subset but 0 is not part of arr element
             else if(i == 0)
             {
                 dp[i][j] = false;
             }
             //emptyset can be a subset
             else if(j == 0)
             {
                 dp[i][j] = true;
             }
            //if we already processed some combination then we have check whether we made this previous sum
             else
             {
                 //checked without me they made the sum of not
                if(dp[i-1][j] == true)
                    dp[i][j] = true;
               
                //some elemets already made sum some
                else
                {
                    int val = arr[i-1];
                 //checking whether I need to play or not and if yes then 
                 //means target is bigger than previous collections 
                    if(j >= val)
                    {
                        //if I add myself here can we check whether remainning run can be possible from my team
                        //j-val -> removing from the target
                        if(dp[i-1][j-val] == true)
                        dp[i][j] = true;
                        
                        
                    }
                }
                
                 
             }
             
         }
     }
     
     
    return dp[n][m];
     
0
2018011192 weeks ago
 What is wrong in this code?
 
int n=sizeof(arr)/sizeof(arr[0]);       bool subset[n+1][sum+1];       for(int i=0;i<=n;i++)       {           subset[i][0]=true;       }       for(int j=1;j<=sum;j++)       {           subset[0][j]=false;       }              for(int i=1;i<=n;i++)       {           for(int j=1;j<=sum;j++)           {               if(j<arr[i-1])               {                   subset[i][j]=subset[i-1][j];               }               if(j>=arr[i-1])               {                   subset[i][j]=subset[i-1][j] || subset[i-1][j-arr[i]];               }           }       }       return subset[n][sum];
0
shivanshukhanna062 weeks ago
SIMPLE MEMOIZED DP SOLUTION HOPE SOMEBODY FIND IT HELPFULint dp[102][10001];   bool solve(vector<int>arr, int sum,int val,int i,int n){       if(dp[i][val]!=-1)return dp[i][val];       if(val>sum)return false;              if(val==sum)return true;       if(i>n)return false;       return dp[i][val]=solve(arr,sum,val+arr[i],i+1,n)||solve(arr,sum,val,i+1,n);          }
   bool isSubsetSum(vector<int>arr, int sum){       // code here        int n=arr.size();       memset(dp,-1,sizeof(dp));       return solve(arr,sum,0,0,n-1);   }
0
b200962 weeks ago
Its giving runtime error in 2nd testcase can someone please help!
 
class Solution{   public:   bool is_sum(vector<int> &arr, int sum, int n,vector<vector<int>> &dp){       if((n<0) || sum<0) return false;       if( sum== 0) return true;       if(dp[sum][n]) return dp[sum][n];       else return dp[sum][n] = (is_sum(arr, sum- arr[n], n-1,dp) || is_sum(arr, sum , n-1,dp));   }   bool isSubsetSum(vector<int> arr, int sum){       vector<vector<int>> dp(100001, vector<int>(101,0));       return is_sum(arr, sum, arr.size()-1, dp);   }}; 
+1
ayush2024cs11342 weeks ago
😉😉😉😉😉 Dp approach just woooow solution!!!!!!!
 
class Solution{   public: 
   bool isSubsetSum(vector<int>arr, int sum){       int n=arr.size();   bool t[n + 1][sum + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) {  if (i == 0)   t[i][j] = false;  if (j == 0)   t[i][j] = true; }}
for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; 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];}          
 
 
 
 
 
 
 
 
+1
uratabhi3 weeks ago
class Solution{   public:   int dp[102][10002];   Solution(){       memset(dp, -1, sizeof(dp));   }      bool issubset(vector<int> &arr, int n, int sum)  {    if(dp[n][sum]!=-1){        return dp[n][sum];    }    if(sum==0) return 1;    if(n<=0 || sum<0)  return 0;
    if(arr[n-1]>sum){        dp[n][sum] = issubset(arr, n-1, sum);    }    else{        dp[n][sum] = issubset(arr, n-1, sum-arr[n-1]) || issubset(arr, n-1, sum);    }
    return dp[n][sum];}   bool isSubsetSum(vector<int>arr, int sum){        int n = int(arr.size());        return issubset(arr, n, sum);   }};
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.