Skip to content

Commit 9607de2

Browse files
added combinational sum
1 parent 973a73b commit 9607de2

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Backtracking/combinational_sum.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""
2+
DESCRIPTION :
3+
Given an array of integers and a sum B, find all unique combinations in the array where the sum is equal to B.
4+
The same number may be chosen from the array any number of times to make B.
5+
NOTE :
6+
1. All numbers will be positive integers.
7+
2. Elements in a combination (a1, a2, …, ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
8+
3. The combinations themselves must be sorted in ascending order.
9+
10+
EXAMPLE :
11+
12+
Input:
13+
N = 4
14+
arr[] = {7,2,6,5}
15+
B = 16
16+
Output:
17+
(2 2 2 2 2 2 2 2)
18+
(2 2 2 2 2 6)
19+
(2 2 2 5 5)
20+
(2 2 5 7)
21+
(2 2 6 6)
22+
(2 7 7)
23+
(5 5 6)
24+
Constraints:
25+
1 <= N <= 30
26+
1 <= A[i] <= 20
27+
1 <= B <= 100
28+
"""
29+
30+
# SOLUTION IN PYTHON3
31+
32+
33+
import atexit
34+
import io
35+
import sys
36+
37+
38+
class Solution:
39+
40+
41+
def combinationalSum(self,A, B):
42+
partialpath=[]
43+
allpath=[]
44+
A = sorted(list(set(A)))
45+
def find(start,target,partialpath,allpath,A):
46+
47+
if(sum(partialpath)==target):
48+
allpath.append(partialpath[:])
49+
return
50+
if(sum(partialpath)>target):
51+
return
52+
for i in range(start,len(A)):
53+
partialpath.append(A[i])
54+
find(i,target,partialpath,allpath,A)
55+
partialpath.pop()
56+
find(0,B,partialpath,allpath,A)
57+
return allpath
58+
59+
60+
if __name__ == '__main__':
61+
test_cases = int(input())
62+
for cases in range(test_cases):
63+
n = int(input())
64+
a = list(map(int,input().strip().split()))
65+
s = int(input())
66+
ob = Solution()
67+
result = ob.combinationalSum(a,s)
68+
if(not len(result)):
69+
print("Empty")
70+
continue
71+
for i in range(len(result)):
72+
print("(", end="")
73+
size = len(result[i])
74+
for j in range(size - 1):
75+
print(result[i][j], end=" ")
76+
if (size):
77+
print(result[i][size - 1], end=")")
78+
else:
79+
print(")", end="")
80+
print()

0 commit comments

Comments
 (0)