注:全文参考
正月点灯笼
b站up主!!
1、求数组内不相邻数的最大和。
arr = [1,2,4,1,7,8,3]
def ret_opt(arr, i):
if i == 0:
return arr[0]
elif i == 1:
return max(arr[0], arr[1])
else:
A = ret_opt(arr, i-2) + arr[i]
B = ret_opt(arr, i-1)
return max(A,B)
def dp_opt(arr):
opt = [1] * len(arr)
if len(arr) == 0:
return arr[0]
elif len(arr) == 1:
return max(arr[0], arr[1])
else:
opt[0] = arr[0]
opt[1] = max(arr[0], arr[1])
for i in range(2,len(arr)):
A = opt[i-2] + arr[i]
B = opt[i-1]
opt[i] = max(A,B)
return opt[-1]
ret = ret_opt(arr, len(arr)-1)
dp = dp_opt(arr)
print(ret, dp)
2、求数组内子集是否能加和等于S。
arr = [3,34,4,12,5,2]
s = 13
def ret_subset(arr, i, s):
if s == 0:
return True
elif i == 0:
return arr[0] == s
elif arr[i] > s:
return ret_subset(arr, i-1, s)
else:
A = ret_subset(arr, i-1, s-arr[i])
B = ret_subset(arr, i-1, s)
return A or B
def dp_subset(arr, s):
subset = [[False] * (s+1) for _ in range(len(arr))]
if arr[0] < s+1:
subset[0][arr[0]] = True
for i in range(len(arr)):
subset[i][0] = True
for i in range(1,len(arr)):
for j in range(1,s+1):
if arr[i] > j:
subset[i][j] = subset[i-1][j]
else:
A = subset[i-1][j-arr[i]]
B = subset[i-1][j]
subset[i][j] = A or B
return subset[-1][-1]
ret = ret_subset(arr, len(arr)-1, s)
dp = dp_subset(arr, s)
print(ret, dp)