Subset Sum (medium)
Problem Statement
Given a set of positive numbers, determine if a subset exists whose sum is equal to a given number ‘S’.
Example 1:
Input: {1, 2, 3, 7}, S=6
Output: True
The given set has a subset whose sum is '6': {1, 2, 3}
Example 2:
Input: {1, 2, 7, 1, 5}, S=10
Output: True
The given set has a subset whose sum is '10': {1, 2, 7}
Example 3:
Input: {1, 3, 4, 8}, S=6
Output: False
The given set does not have any subset whose sum is equal to '6'.
Try it yourself
Try solving this question here:
class SubsetSum {public boolean canPartition(int[] num, int sum) {// TODO: Write your code herereturn false;}public static void main(String[] args) {SubsetSum ss = new SubsetSum();int[] num = { 1, 2, 3, 7 };System.out.println(ss.canPartition(num, 6));num = new int[] { 1, 2, 7, 1, 5 };System.out.println(ss.canPartition(num, 10));num = new int[] { 1, 3, 4, 8 };System.out.println(ss.canPartition(num, 6));}}
Basic Solution
This problem follows the 0/1 Knapsack pattern and is quite similar to ...