File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ Aim: From a list of integers, check and return a set of integers whose sum
3
+ will be equal to the target value K.
4
+
5
+ '''
6
+
7
+ # Main Recursive function to find the desired Subset Sum
8
+ def Subset_Sum (li , target , ans = []):
9
+
10
+ # Base Cases
11
+ if target == 0 and ans != []:
12
+ return ans
13
+
14
+ elif li == []:
15
+ return False
16
+
17
+ # li[0] is not included in the answer Subset
18
+ temp = Subset_Sum (li [1 :], target , ans )
19
+ if temp :
20
+ return temp
21
+
22
+ # li[0] included in the answer Subset
23
+ temp = Subset_Sum (li [1 :], target - li [0 ], ans + [li [0 ]])
24
+
25
+ return temp
26
+
27
+ # --------------------------- DRIVER CODE------------------------------
28
+
29
+ if __name__ == "__main__" :
30
+
31
+ li = [int (i ) for i in input ("Enter the List of Integers: " ).split ()]
32
+ Target = int (input ("Enter the Target value: " ))
33
+
34
+ ans = Subset_Sum (li , Target )
35
+ if not ans :
36
+ print ("No Subset Sum matched to the Target" )
37
+ else :
38
+ print ("The Required Subset is : " , * ans )
39
+
40
+ '''
41
+
42
+ Sample Input:
43
+ Enter the List of Integers: -1 2 6 7 -4 7 5 -2
44
+ Enter the Target value: 0
45
+
46
+ Sample Output:
47
+ The Required Subset is : 6 -4 -2
48
+
49
+ Explanation:
50
+ 6 - 4 - 2 = 0, the required result
51
+
52
+ COMPLEXITY:
53
+
54
+ Time Complexity: O(2^N)
55
+ Space complexity: O(N)
56
+
57
+ '''
You can’t perform that action at this time.
0 commit comments