给定一个由N个整数组成的整数数组arr [] ,检查是否可以将给定数组划分为K个相等总和的非空子集,以使每个数组元素都是单个子集的一部分。
例子:
Input: arr[] = {2, 1, 4, 5, 6}, K = 3
Output: Yes
Explanation:
Possible subsets of given array are {2, 4}, (1, 5} and {6}
Input: arr[] = {2, 1, 5, 5, 6}, K = 3
Output: No
对于递归方法,请参阅将集合划分为具有相等总和的K个子集。
方法:
请按照以下步骤解决问题:
- 这个想法是使用mask来确定当前状态。当前状态将告诉我们已经形成的子集(已经选择了哪些数字)。
例如: arr [] = [2、1、4、3、5、6、2], mask =(1100101),这意味着{,1、5、2}已在当前掩码中选择。 - 对于任何当前状态掩码,将基于以下两个条件将第j个元素添加到其中:
- The jth bit is not set in the mask (mask&(1<
) - sum (mask) + arr[j] <= target ( where target = (Sum of array elements) / K)
- The jth bit is not set in the mask (mask&(1<
- 对表dp []进行维护,使dp [i]将元素的总和存储在掩码i中。因此,dp转换将是:
dp[i | (1 << j)] = (dp[i] + arr[j]) % target
Illustration:
arr [ ] = [4, 3, 2, 3, 5, 2, 1], K = 4, tar = 5
dp[“1100101”] implies that { 4, 3, 5, 1 } are chosen
Hence, Sum = 4 + 3 + 5 + 1 = 13, 13 % 5 = 3.
Hence, dp[“1100101”] = 3If dp[“11111…1111”] == 0 then that means we can find the solution.
下面是上述方法的实现:
C++
// C++ program to check if the
// given array can be partitioned
// into K subsets with equal sum
#include
using namespace std;
// Function to check whether
// K required partitions
// are possible or not
bool isKPartitionPossible(int arr[],
int N, int K)
{
if (K == 1)
// Return true as the
// entire array is the
// answer
return true;
// If total number of
// partitions exceeds
// size of the array
if (N < K)
return false;
int sum = 0;
for (int i = 0; i < N; i++)
sum += arr[i];
// If the array sum is not
// divisible by K
if (sum % K != 0)
// No such partitions are
// possible
return false;
// Required sum of
// each subset
int target = sum / K;
// Initialize dp array with -1
int dp[(1 << 15)];
for (int i = 0; i < (1 << N); i++)
dp[i] = -1;
// Sum of empty subset
// is zero
dp[0] = 0;
// Iterate over all subsets/masks
for (int mask = 0; mask < (1 << N); mask++) {
// if current mask is invalid, continue
if (dp[mask] == -1)
continue;
// Iterate over all array elements
for (int i = 0; i < N; i++) {
// Check if the current element
// can be added to the current
// subset/mask
if (!(mask & (1 << i))
&& dp[mask]
+ arr[i]
<= target) {
// transition
dp[mask | (1 << i)]
= (dp[mask]
+ arr[i])
% target;
}
}
}
if (dp[(1 << N) - 1] == 0)
return true;
else
return false;
}
// Driver Code
int main()
{
int arr[] = { 2, 1, 4, 5, 3, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 3;
if (isKPartitionPossible(arr, N, K)) {
cout << "Partitions into equal ";
cout << "sum is possible.\n";
}
else {
cout << "Partitions into equal ";
cout << "sum is not possible.\n";
}
}
Java
// Java program to check if the
// given array can be partitioned
// into K subsets with equal sum
import java.util.*;
class GFG{
// Function to check whether
// K required partitions
// are possible or not
static boolean isKPartitionPossible(int arr[],
int N, int K)
{
if (K == 1)
// Return true as the
// entire array is the
// answer
return true;
// If total number of
// partitions exceeds
// size of the array
if (N < K)
return false;
int sum = 0;
for(int i = 0; i < N; i++)
sum += arr[i];
// If the array sum is not
// divisible by K
if (sum % K != 0)
// No such partitions are
// possible
return false;
// Required sum of
// each subset
int target = sum / K;
// Initialize dp array with -1
int []dp = new int[(1 << 15)];
for(int i = 0; i < (1 << N); i++)
dp[i] = -1;
// Sum of empty subset
// is zero
dp[0] = 0;
// Iterate over all subsets/masks
for(int mask = 0; mask < (1 << N); mask++)
{
// if current mask is invalid, continue
if (dp[mask] == -1)
continue;
// Iterate over all array elements
for(int i = 0; i < N; i++)
{
// Check if the current element
// can be added to the current
// subset/mask
if (((mask & (1 << i)) == 0) &&
dp[mask] + arr[i] <= target)
{
// Transition
dp[mask | (1 << i)] = (dp[mask] +
arr[i]) %
target;
}
}
}
if (dp[(1 << N) - 1] == 0)
return true;
else
return false;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 2, 1, 4, 5, 3, 3 };
int N = arr.length;
int K = 3;
if (isKPartitionPossible(arr, N, K))
{
System.out.print("Partitions into equal ");
System.out.print("sum is possible.\n");
}
else
{
System.out.print("Partitions into equal ");
System.out.print("sum is not possible.\n");
}
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program to check if the
# given array can be partitioned
# into K subsets with equal sum
# Function to check whether
# K required partitions
# are possible or not
def isKPartitionPossible(arr, N, K):
if (K == 1):
# Return true as the
# entire array is the
# answer
return True
# If total number of
# partitions exceeds
# size of the array
if (N < K):
return False
sum = 0
for i in range(N):
sum += arr[i]
# If the array sum is not
# divisible by K
if (sum % K != 0):
# No such partitions are
# possible
return False
# Required sum of
# each subset
target = sum / K
# Initialize dp array with -1
dp = [0 for i in range(1 << 15)]
for i in range((1 << N)):
dp[i] = -1
# Sum of empty subset
# is zero
dp[0] = 0
# Iterate over all subsets/masks
for mask in range((1 << N)):
# If current mask is invalid,
# continue
if (dp[mask] == -1):
continue
# Iterate over all array elements
for i in range(N):
# Check if the current element
# can be added to the current
# subset/mask
if ((mask & (1 << i) == 0) and
dp[mask] + arr[i] <= target):
# Transition
dp[mask | (1 << i)] = ((dp[mask] +
arr[i]) %
target)
if (dp[(1 << N) - 1] == 0):
return True
else:
return False
# Driver Code
if __name__ == '__main__':
arr = [ 2, 1, 4, 5, 3, 3 ]
N = len(arr)
K = 3
if (isKPartitionPossible(arr, N, K)):
print("Partitions into equal "\
"sum is possible.")
else:
print("Partitions into equal sum "\
"is not possible.")
# This code is contributed by Surendra_Gangwar
C#
// C# program to check if the
// given array can be partitioned
// into K subsets with equal sum
using System;
class GFG{
// Function to check whether
// K required partitions
// are possible or not
static bool isKPartitionPossible(int []arr,
int N, int K)
{
if (K == 1)
// Return true as the
// entire array is the
// answer
return true;
// If total number of
// partitions exceeds
// size of the array
if (N < K)
return false;
int sum = 0;
for(int i = 0; i < N; i++)
sum += arr[i];
// If the array sum is not
// divisible by K
if (sum % K != 0)
// No such partitions are
// possible
return false;
// Required sum of
// each subset
int target = sum / K;
// Initialize dp array with -1
int []dp = new int[(1 << 15)];
for(int i = 0; i < (1 << N); i++)
dp[i] = -1;
// Sum of empty subset
// is zero
dp[0] = 0;
// Iterate over all subsets/masks
for(int mask = 0; mask < (1 << N); mask++)
{
// If current mask is invalid, continue
if (dp[mask] == -1)
continue;
// Iterate over all array elements
for(int i = 0; i < N; i++)
{
// Check if the current element
// can be added to the current
// subset/mask
if (((mask & (1 << i)) == 0) &&
dp[mask] + arr[i] <= target)
{
// Transition
dp[mask | (1 << i)] = (dp[mask] +
arr[i]) %
target;
}
}
}
if (dp[(1 << N) - 1] == 0)
return true;
else
return false;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 2, 1, 4, 5, 3, 3 };
int N = arr.Length;
int K = 3;
if (isKPartitionPossible(arr, N, K))
{
Console.Write("Partitions into equal ");
Console.Write("sum is possible.\n");
}
else
{
Console.Write("Partitions into equal ");
Console.Write("sum is not possible.\n");
}
}
}
// This code is contributed by Amit Katiyar
输出:
Partitions into equal sum is possible.
时间复杂度: O(N * 2 N )
辅助空间: O(2 N )