给定一个由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[] 中的最大元素
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live