forked from playerg7/Contribute
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubset-sum-problem-osum-space.py
More file actions
37 lines (30 loc) · 931 Bytes
/
Copy pathsubset-sum-problem-osum-space.py
File metadata and controls
37 lines (30 loc) · 931 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Returns true if there exists a subset
# with given sum in arr[]
def isSubsetSum(arr, n, sum):
# The value of subset[i%2][j] will be true
# if there exists a subset of sum j in
# arr[0, 1, ...., i-1]
subset = [ [False for j in range(sum + 1)] for i in range(3) ]
for i in range(n + 1):
for j in range(sum + 1):
# A subset with sum 0 is always possible
if (j == 0):
subset[i % 2][j] = True
# If there exists no element no sum
# is possible
else if (i == 0):
subset[i % 2][j] = False
else if (arr[i - 1] <= j):
subset[i % 2][j] = subset[(i + 1) % 2][j - arr[i - 1]] or subset[(i + 1)
% 2][j]
else:
subset[i % 2][j] = subset[(i + 1) % 2][j]
return subset[n % 2][sum]
# Driver code
arr = [ 6, 2, 5 ]
sum = 7
n = len(arr)
if (isSubsetSum(arr, n, sum) == True):
print ("There exists a subset with given sum")
else:
print ("No subset exists with given sum")