Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Subset Sum Problem solution #93

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions dp/subset_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# A Dynamic Programming solution for subset
# sum problem
# Returns true if there is a subset of
# with sum equal to the given sum

def isSubsetSum(set, n, sum):

dp =([[False for i in range(sum + 1)]
for i in range(n + 1)])

for i in range(n + 1):
dp[i][0] = True

for i in range(1, sum + 1):
dp[0][i]= False

for i in range(1, n + 1):
for j in range(1, sum + 1):
if j < set[i-1]:
dp[i][j] = dp[i-1][j]
if j >= set[i-1]:
dp[i][j] = (dp[i - 1][j] or
dp[i - 1][j-set[i - 1]])
return dp[n][sum]

if __name__=='__main__':
set = [3, 34, 44, 1299, 5, 29]
sum = 9
n = len(set)
if (isSubsetSum(set, n, sum) == True):
print("Subset found")
else:
print("No such subset")