![]() |
VOOZH | about |
Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset.
Examples:
Input: arr[] = [2, 1, 4, 5, 6], k = 3
Output: true
Explanation: Possible subsets of the given array are [2, 4], [1, 5] and [6]Input: arr[] = [2, 1, 5, 5, 6], k = 3
Output: false
Explanation: It is not possible to divide above array into 3 parts with equal sum.
Table of Content
We recursively explore all possible combinations for each of the k subsets. This is achieved by tracking the sum of the current subset and using a boolean array (taken) to check if an element has already been included in a subset or not.
Base Cases:
if these condition are met, the task reduces to dividing the array into k subsets , each with sum equal to arraySum/k.
Recursive Cases:
The recursive function attempts to add elements to each subset:
Steps
k == 1, n < k, sum % k != 0)sum / k and initialize taken[] and subsetSum[]k-1 subsets are formed, return truetrue
The idea is to use mask to determine the current state. The current state tells us about the subset already formed (which numbers are already selected).
For example: arr[] = [2, 1, 4, 3, 5, 6, 2], mask = (1100101), which means that [2, 1, 5, 2] are already chosen in the current mask.
For any current statemask, the jth element will be added to it based on the following two conditions:
- The jth bit is not set in the mask (mask & (1<<j) == 0)
- sum (mask) + arr[j] <= target ( where target = (sum of array elements) / k)
Maintain a table dp[] such that dp[i] store the sum of elements in mask i. So, the dp transitions will be:
dp[i | (1 << j)] = (dp[i] + arr[j]) % target
k, set target dp[mask] to store current subset sum, initialize dp[0] = 0j if sum ≤ target dp[newMask] = (dp[mask] + arr[j]) % targettrue