|
| 1 | +# A Dynamic Programming solution for subset sum problem |
| 2 | +# Returns true if there is a subset of |
| 3 | +# set[] with sun equal to given sum |
| 4 | + |
| 5 | +# Returns true if there is a subset of set[] |
| 6 | +# with sun equal to given sum |
| 7 | +def isSubsetSum(set, n, sum): |
| 8 | + # The value of subset[i][j] will be |
| 9 | + # true if there is a |
| 10 | + # subset of set[0..j-1] with sum equal to i |
| 11 | + subset = ([[False for i in range(sum + 1)] |
| 12 | + for i in range(n + 1)]) |
| 13 | + |
| 14 | + # If sum is 0, then answer is true |
| 15 | + for i in range(n + 1): |
| 16 | + subset[i][0] = True |
| 17 | + |
| 18 | + # If sum is not 0 and set is empty, |
| 19 | + # then answer is false |
| 20 | + for i in range(1, sum + 1): |
| 21 | + subset[0][i] = False |
| 22 | + |
| 23 | + # Fill the subset table in botton up manner |
| 24 | + for i in range(1, n + 1): |
| 25 | + for j in range(1, sum + 1): |
| 26 | + if j < set[i - 1]: |
| 27 | + subset[i][j] = subset[i - 1][j] |
| 28 | + if j >= set[i - 1]: |
| 29 | + subset[i][j] = (subset[i - 1][j] or |
| 30 | + subset[i - 1][j - set[i - 1]]) |
| 31 | + |
| 32 | + # uncomment this code to print table |
| 33 | + # for i in range(n+1): |
| 34 | + # for j in range(sum+1): |
| 35 | + # print (subset[i][j],end=" ") |
| 36 | + # print() |
| 37 | + return subset[n][sum] |
| 38 | + |
| 39 | + |
| 40 | +# Driver program to test above function |
| 41 | +if __name__ == '__main__': |
| 42 | + set = [3, 34, 4, 12, 5, 2] |
| 43 | + sum = 9 |
| 44 | + n = len(set) |
| 45 | + if (isSubsetSum(set, n, sum) == True): |
| 46 | + print("Found a subset with given sum") |
| 47 | + else: |
| 48 | + print("No subset with given sum") |
| 49 | + |
| 50 | + # This code is contributed by |
| 51 | +# sahil shelangia. |
0 commit comments