// C++ program to partition an array into K subsets with
// equal sum
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
// Helper function to check if we can partition the array
// into K subsets
bool canPartitionKSubsetsUtil(vector<int>& nums,
vector<bool>& visited,
int start_index, int k,
int cur_sum, int target_sum)
{
if (k == 1)
// Only one partition left, so the remaining
// elements must form the last subset
return true;
if (cur_sum == target_sum)
// Current partition is done, move on to the next
// partition
return canPartitionKSubsetsUtil(
nums, visited, 0, k - 1, 0, target_sum);
// Try including each number in the current partition
for (int i = start_index; i < nums.size(); i++) {
if (!visited[i]
&& cur_sum + nums[i] <= target_sum) {
// Mark the number as visited
visited[i] = true;
// Recursively try to form the partition
// including the current number
if (canPartitionKSubsetsUtil(
nums, visited, i + 1, k,
cur_sum + nums[i], target_sum))
return true;
// Backtrack
visited[i] = false;
}
}
// Partitioning is not possible with the current
// configuration
return false;
}
// Function to check if the array can be partitioned into K
// subsets with equal sum
bool canPartitionKSubsets(vector<int>& nums, int k)
{
// Calculate the total sum of the array
int total_sum = accumulate(nums.begin(), nums.end(), 0);
if (total_sum % k != 0)
// If total sum is not divisible by k, partitioning
// is not possible
return false;
// Keep track of visited elements
vector<bool> visited(nums.size(), false);
// Start the partitioning process
return canPartitionKSubsetsUtil(nums, visited, 0, k, 0,
total_sum / k);
}
int main()
{
vector<int> arr = { 2, 1, 4, 5, 3, 3 };
int k = 3;
// Check if partitioning into equal sum subsets is
// possible
if (canPartitionKSubsets(arr, k))
cout << "Partitions into equal sum is possible."
<< endl;
else
cout << "Partitions into equal sum is not possible."
<< endl;
return 0;
}