```import sys
# Function to find the smallest subarray
# with sum greater than or equal target
def minlt(arr, target, n):
# DP table to store the
# computed subproblems
dp = [[-1 for _ in range(target + 1)]
for _ in range(len(arr)+1)]
#pf = [-1 for _ in range(len(arr)+1)]
for i in range(len(arr)+1):
# Initialize first
# column with 0
dp[i][0] = 0
for j in range(target + 1):
# Initialize first
# row with 0
dp[0][j] = sys.maxsize
for i in range(1, len(arr)+1):
for j in range(1, target + 1):
# Check for invalid condition
if arr[i-1] > j:
dp[i][j] = dp[i-1][j]
else:
# Fill up the dp table
#if dp[i-1][j] == 1 or (1 + dp[i][j-arr[i-1]]) == sys.maxsize:
dp[i][j] = min(dp[i-1][j],
1 + dp[i][j-arr[i-1]])
return dp[-1][-1]
# Print the minimum length
if dp[-1][-1] == sys.maxsize:
return(-1)
else:
return dp[-1][-1]
# Driver Code
arr = [10,9,2,1]
target = 11
n = len(arr)
print(minlt(arr, target, n))
有人能修改这个程序,使它打印最小的子数组而不是长度吗此代码只返回最小子数组的长度,其和大于或等于给定目标提前感谢
以下是In如何实现您想要的功能。
#First the function definition
def minlt(arr, target):
rslt = (None, None, None) #tuple containing the (subarray_sum, subarray_start, sub_array_length)
for i in range(len(arr)-1):
for k in range(i+1, len(arr)):
arsm = sum(arr[i:k])
if arsm >= target:
if rslt[0] == None or rslt[2] > k-i+1 or (rslt[2] == k-i+1 and rslt[0] > arsm):
rslt = (arsm, i, k-i+1)
return arr[rslt[1]:rslt[2]]
然后呼叫设置:
arr = [10,9,2,1]
target = 11
minlt(arr, target)
收益率:
[9, 2]