Solution: The Partition Problem
This review provides a detailed analysis of the ways to solve the partition problem.
Solution #1: Brute force
Let’s start by looking at the brute force solution to solve this problem first:
Press + to interact
class Partition{public static boolean canPartitionRecursive(int num[], int sum, int currentIndex){int numLength = num.length;// base checkif (sum == 0)return true;if (numLength == 0 || currentIndex >= numLength)return false;// recursive call after choosing the number at the currentIndex// if the number at currentIndex exceeds the sum, we shouldn't process thisif (num[currentIndex] <= sum) {if (canPartitionRecursive(num, sum - num[currentIndex], currentIndex + 1))return true;}// recursive call after excluding the number at the currentIndexreturn canPartitionRecursive(num, sum, currentIndex + 1);}public static Object canPartition(int num[]){int numLength = num.length;int sum = 0;for (int i = 0; i < numLength; i++)sum += num[i];// if 'sum' is an odd number, we can't have two subsets with equal sumif (sum % 2 != 0)return false;return canPartitionRecursive(num, sum / 2, 0);}public static void main(String args[]){int set1[] = {1, 2, 3, 4};System.out.println(Arrays.toString(set1) + "\t--->\t" + canPartition(set1));int set2[] = {1, 1, 3, 4, 7};System.out.println(Arrays.toString(set2) + "\t--->\t" + canPartition(set2));int set3[] = {2, 3, 4, 6};System.out.println(Arrays.toString(set3) + "\t--->\t" + canPartition(set3));}};
Explanation
This problem is very similar to the 0/1 knapsack. It essentially follows the same pattern. This solution tries all the combinations of partitioning the given numbers into two sets to see if any pair of sets have an equal sum.
If represents the total sum of all the given numbers, then the two equal subsets must have a sum equal to ...
Access this course and 1400+ top-rated courses and projects.