【发布时间】:2021-01-10 19:34:34
【问题描述】:
```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))
任何人都可以对这个程序进行更改,使其打印最小的子数组而不是长度 此代码仅返回总和大于或等于给定目标的最小子数组的长度 提前致谢
【问题讨论】:
-
鉴于您确定的输入,您将什么定义为可能的子数组?当我解释一个子数组时,总和 >= 目标的子数组包括:[10,9,2,1]、[10,9,2]、[10,9]、[9,2,1] 和 [ 9,2] 并且最小的子数组 >= 目标将是 [9,2]。它是否正确?我问的原因是我不明白使用 sys.maxsize 的理由。
-
是的,sys.maxsize 在 c++ 中是 INT_MAX
-
在 C++ 中,INT_MAX 指定一个整数变量,它等于最大整数限制。运行应用程序的系统。在 Python 中 sys.max_size maxsize 有很大的不同。 sys 模块获取数据类型 Py_ssize_t 的变量可以存储的最大值。它本质上是 Python 平台的字长。您正在寻找的是 int(math.inf)。尽管在您的情况下, sys.maxsize 返回的值也可以解决问题。
标签: python-3.x dynamic-programming