-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
445f8b2
commit 0887629
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
def isSubsetSum(set,n, sum) : | ||
|
||
# Base Cases | ||
if (sum == 0) : | ||
return True | ||
if (n == 0 and sum != 0) : | ||
return False | ||
|
||
# If last element is greater than | ||
# sum, then ignore it | ||
if (set[n - 1] > sum) : | ||
return isSubsetSum(set, n - 1, sum) | ||
|
||
# else, check if sum can be obtained | ||
# by any of the following | ||
# (a) including the last element | ||
# (b) excluding the last element | ||
return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1, sum-set[n-1]) | ||
|
||
|
||
# Test case | ||
set = [3, 34, 4, 12, 5, 2] | ||
sum = 100 | ||
n = len(set) | ||
if (isSubsetSum(set, n, sum) == True) : | ||
print("Found a subset with given sum") | ||
else : | ||
print("No subset with given sum") |