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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
import numpy as np
def rec_subset(arr, i, S): if S == 0: return True
elif i == 0: return arr[0] == S
elif arr[i] > S: return rec_subset(arr, i-1, S)
else: A = rec_subset(arr, i-1, S-arr[i]) B = rec_subset(arr, i-1, S) return A or B
def dp_subset(arr, S): subset = np.zeros((len(arr), S + 1), dtype=bool) subset[:, 0] = True subset[0, :] = False subset[0, arr[0]] = True for i in range(1, len(arr)): for s in range(1, S + 1):
if arr[i] > s: subset[i, s] = subset[i-1, s]
else: A = subset[i-1, s-arr[i]] B = subset[i-1, s] subset[i, s] = A or B return subset[-1, -1]
if __name__ == "__main__": arr = [3, 34, 4, 12, 5, 2] print(dp_subset(arr, 9)) print(dp_subset(arr, 10)) print(dp_subset(arr, 11)) print(dp_subset(arr, 12)) print(dp_subset(arr, 13))
|