Solution: The Partition Problem
Explore various approaches to solving the partition problem in detail.
Solution 1: Brute force
using System;class Program{/// <summary>/// Checks if two sub-arrays have equal sum or not./// </summary>/// <param name="set">Integer array containing positive numbers only.</param>/// <returns>True if two sub-arrays have equal sum, otherwise false.</returns>public static bool CanPartition(int[] set){int setLength = set.Length;int sum = 0;foreach (int num in set){sum += num;}// if 'sum' is an odd number, we can't have two subsets with equal sumif (sum % 2 != 0){return false;}return CanPartitionRecursive(set, setLength, sum / 2, 0);}/// <summary>/// Checks if two sub-arrays have equal sum or not./// </summary>/// <param name="set">Integer array containing positive numbers only.</param>/// <param name="setLength">Length of the array.</param>/// <param name="sum">Stores sum of the sub-array.</param>/// <param name="currentIndex">Index of the sub-array.</param>/// <returns>True if two sub-arrays have equal sum, otherwise false.</returns>static bool CanPartitionRecursive(int[] set, int setLength, int sum, int currentIndex){// base checkif (sum == 0){return true;}if (setLength == 0 || currentIndex >= setLength){return false;}// recursive call after choosing the number at the currentIndex// if the number at currentIndex exceeds the sum, we shouldn't process thisif (set[currentIndex] <= sum){if (CanPartitionRecursive(set, setLength, sum - set[currentIndex], currentIndex + 1)){return true;}}// recursive call after excluding the number at the currentIndexreturn CanPartitionRecursive(set, setLength, sum, currentIndex + 1);}// Driver code to test the above methodpublic static void Main(string[] args){int[] set1 = { 1, 2, 3, 4 };Console.WriteLine(CanPartition(set1));int[] set2 = { 1, 1, 3, 4, 7 };Console.WriteLine(CanPartition(set2));int[] set3 = { 2, 3, 4, 6 };Console.WriteLine(CanPartition(set3));}}
Explanation
This problem is very similar to the 0/1 knapsack problem. 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 . So, our problem is to find a subset of the given numbers that has a total sum of . So, our algorithm looks like this:
For each number :
- We create a new set with number