Python program to get all subsets having sum x
We are given a list of n numbers and a number x, the task is to write a python program to find out all possible subsets of the list such that their sum is x.
Examples:
Input: arr = [2, 4, 5, 9], x = 15
Output: [2, 4, 9]
15 can be obtained by adding 2, 4 and 9 from the given list.
Input : arr = [10, 20, 25, 50, 70, 90], x = 80
Output : [10, 70]
[10, 20, 50]
80 can be obtained by adding 10 and 70 or by adding 10, 20 and 50 from the given list.
Approach #1:
It is a Brute Force approach. Find all possible subset sums of the given list and check if the sum is equal to x. The time complexity using this approach would be O(2^n) which is quite large.
Python3
from itertools import combinations
def subsetSum(n, arr, x):
for i in range (n + 1 ):
for subset in combinations(arr, i):
if sum (subset) = = x:
print ( list (subset))
n = 6
arr = [ 10 , 20 , 25 , 50 , 70 , 90 ]
x = 80
subsetSum(n, arr, x)
|
Output:
[10, 70]
[10, 20, 50]
Approach #2:
Meet in the middle is a technique that divides the search space into two equal-sized parts, performs a separate search on both the parts and then combines the search results. Using this technique, the two searches may require less time than one large search and turn the time complexity from O(2^n) to O(2^(n/2)).
Python3
from itertools import combinations
def subsetSum(li, comb, sums):
for i in range ( len (li) + 1 ):
for subset in combinations(li, i):
comb.append( list (subset))
sums.append( sum (subset))
def calcSubsets(n, arr, x):
arr1, arr2 = arr[:n / / 2 ], arr[n / / 2 :]
comb1, sums1 = [], []
subsetSum(arr1, comb1, sums1)
comb2, sums2 = [], []
subsetSum(arr2, comb2, sums2)
for i in range ( len (sums1)):
for j in range ( len (sums2)):
if sums1[i] + sums2[j] = = x:
print (comb1[i] + comb2[j])
n = 6
arr = [ 10 , 20 , 25 , 50 , 70 , 90 ]
x = 80
calcSubsets(n, arr, x)
|
Output:
[10, 70]
[10, 20, 50]
Last Updated :
25 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...