Skip to content

Commit 90ff8f0

Browse files
Update combinational_sum.py
1 parent 9607de2 commit 90ff8f0

File tree

1 file changed

+74
-60
lines changed

1 file changed

+74
-60
lines changed

Backtracking/combinational_sum.py

Lines changed: 74 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,94 @@
11
"""
22
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.
3+
Given an array of integers arr[] and a target number k, write a program to find all unique combinations in arr[]
4+
such that the sum of all integers in the combination is equal to k.
5+
The same repeated number may be chosen from arr[] unlimited number of times.
6+
57
NOTE :
68
1. All numbers will be positive integers.
79
2. Elements in a combination (a1, a2, …, ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
810
3. The combinations themselves must be sorted in ascending order.
11+
4. The solution set must not contain duplicate combinations.
912
1013
EXAMPLE :
1114
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:
15+
Given array 2,3,6,7 and target 7,
16+
A solution set is:
17+
[2, 2, 3]
18+
19+
CONSTRAINTS:
2520
1 <= N <= 30
2621
1 <= A[i] <= 20
2722
1 <= B <= 100
28-
"""
2923
30-
# SOLUTION IN PYTHON3
24+
SOLUTION APPROACH :
3125
26+
In every recursion run, you either include the element in the combination or you don’t.
27+
To account for multiple occurrences of an element,
28+
make sure you call the next function without incrementing the current index.
3229
33-
import atexit
34-
import io
35-
import sys
30+
"""
31+
# SOLUTION IN PYTHON3
3632

3733

3834
class Solution:
35+
# @param A : list of integers
36+
# @param B : integer
37+
# @return a list of list of integers
38+
def combinationSum(self, A, B):
39+
# Remove duplicate and sort since each element can be repeated
40+
# in combination either way.
41+
# Removing duplicates here helps us avoid removing them from the final result.
42+
A=sorted(set(A))
43+
# if the target sum is less than 2 or the lis A is empty,
44+
# then retirn an empty list
45+
if B<2 or len(A)==0:
46+
return [[]]
47+
48+
49+
result=[]
50+
comb=[]
51+
index=0
52+
self.find(result, comb, A, B, index)
53+
return result
3954

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-
55+
def find(self, result, comb, A, B, index):
56+
# The recursion will nest until we hit the target. At this point we append and return.
57+
if sum(comb) == B:
58+
result.append(comb[:])
59+
return
60+
# If the sum is bigger, we also terminate the recursion chain.
61+
if sum(comb)>B:
62+
return
63+
64+
for i in range(index, len(A)):
65+
comb.append(A[i])
66+
# Start from same index since an element can be repeated.
67+
self.find(result, comb, A, B, i)
68+
comb.pop()
69+
70+
'''
71+
72+
Sample Input : A = [2,3,5], B = 8
73+
Output:
74+
[
75+
[2,2,2,2],
76+
[2,3,3],
77+
[3,5]
78+
]
79+
80+
EXPLANATION:
81+
All the unique combinations whose sum is 8 is printed.
82+
2+2+2+2 = 8
83+
2+3+3 = 8
84+
3+5 = 8
85+
86+
COMPLEXITY ANALYSIS :
87+
88+
Time Complexity -> O(l^k)
89+
Where l is the length of the array, k is the length of the longest possible combination (namely target / minInArray).
90+
91+
Space Complexity -> O(k)
92+
for storing the path, which could be k long at most.
5993
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()
94+
'''

0 commit comments

Comments
 (0)