Subset Sum Easy

Please check the code. In my approach, I made a ArrayList of integer array in which all subsets of inputted array are stored, then checked each subset one by one.
It’s giving wrong answer in 2 out of 2 testcases.

Hi @vivek21,
See first of all your code will not give you correct output if the answer is “No”.
See this example:
2
4
1 2 3 4
4
1 2 3 4
Correct Output:
No
No
Your Output:
No

Take an int flag and put it inside the value and change its value. Also, remove the return keyword and use break.

And finally, you are always taking subsets and including the first element.
What if there’s an example:
4
10 9 -3 -6
The answer will be Yes but your code will give No.

  1. You can approach this problem as the subset sum problem. In which you are given a target sum as 0.
  2. Every element has two options, either it can be a part of the subset or it cant be a part of the subset.
  3. In the base case you can check whether the sum is equal to 0.
  4. If it is equal to 0 then you can update a boolean variable or flag variable.
  5. After the execution of your subset function you can check the value of that check variable and print the answer accordingly.
1 Like