给定一个由N个整数组成的数组A [] ,任务是将数组A []拆分为多个子集,这些子集的总和相等且长度等于数组B []中的元素。
例子:
Input: A[] = {17, 13, 21, 20, 50, 29}, B[] = {2, 3, 1}
Output:
21 29
17 13 20
50
Input: A[] = { 1, 2, 3, 4, 5, 6}, B[] = { 2, 2, 2}
Output:
1 6
2 5
3 4
方法:请按照以下步骤解决问题:
- 由于已经给出了子集的数量,因此请计算每个子集的总和。
- 遍历数组B []的每个元素,找到长度B [i]的每种可能的组合,并检查组合的总和是否等于所需的总和。
- 对每个数组元素B [i]重复上述步骤,并打印最终答案
下面是上述方法的实现:
Python
# Python Program to implement
# the above approach
from itertools import combinations
# Function to split elements of first
# array into subsets of size given as
# elements in the second array
def main(A, B):
# Required sum of subsets
req_sum = sum(A) // len(B)
# Stores the subsets
final = []
# Iterate the array B[]
for i in B:
# Generate all possible
# combination of length B[i]
temp = list(combinations(A, i))
# Iterate over all the combinations
for j in temp:
# If the sum is equal to the
# required sum of subsets
if(sum(j) == req_sum):
# Store the subset
temp = list(j)
final.append(temp)
for k in temp:
# Removing the subset
# from the array
A.remove(k)
break
# Printing the final result
print(final)
# Driver Code
if __name__ == '__main__':
# Value of array A and B
A = [1, 2, 3, 4, 5, 6]
B = [2, 2, 2]
# Function call
main(A, B)
输出:
[[1, 6], [2, 5], [3, 4]]
时间复杂度: O(N 3 )
辅助空间: O(2 maxm ),其中maxm是数组B []中的最大元素