这与0-1背包问题没有太大区别。
Zero-initialize a matrix with S+U rows and N columns(U is the largest list value)
Zero-initialize a bit array A with S+U elements
For each value (v) in the list:
For each j<S:
If M[N-1,j] != 0 and M[N-1, j + v] == 0:
M[N-1, j + v] = v
A[j + v] = true
For i=N-2 .. 0:
For each j<S:
If M[i,j] != 0 and M[i+1, j + v] == 0:
M[i+1, j + v] = v
M[0,v] = v
Find first nonzero element in M[N-1,S..S+U]
Reconstruct other elements of the subset by subtracting found value from its\
index and using the result as index in preceding column of the matrix\
(or in the last column, depending on the corresponding bit in 'A').
时间复杂度为 O(L*N*S),其中 L 是列表的长度,N 和 S 有限制。
空间复杂度为 O(L*N)。
Zero-initialize an integer array A with S+U elements
i=0
For each value (v) in the list:
For each j<S:
If A[j] != 0 and A[j + v] < A[j] + 1:
A[j + v] = A[j] + 1
V[i,j + v] = v
P[i,j + v] = I[j]
I[j + v] = i
If A[v] == 0:
A[v] = 1
I[v] = i
++i
Find first element in A[S..S+U] with value not less than N
Reconstruct elements of the subset using matrices V and P.
时间复杂度为 O(L*S),其中 L 是列表的长度,S 是给定的限制。
空间复杂度为 O(L*S)。
也最小化子集大小的算法:
Zero-initialize a boolean matrix with S+U rows and N columns\
(U is the largest list value)
Zero-initialize an integer array A with S+U elements
i=0
For each value (v) in the list:
For each j<S:
If A[j] != 0 and (A[j + v] == 0) || (A[j + v] > A[j] + 1)):
A[j + v] = A[j] + 1
V[i,N-1,j + v] = v
P[i,N-1,j + v] = (I[j,N-1],N-1)
I[j+v,N-1] = i
For k=N-2 .. 0:
For each j<S:
If M[k,j] and not M[k+1, j + v]:
M[k+1, j + v] = true
V[i,k+1,j + v] = v
P[i,k+1,j + v] = (I[j,k],k)
I[j+v,k+1] = i
For each j<S:
If M[N-1, j]:
A[j] = N-1
M[0,v] = true
I[v,0] = i
++i
Find first nonzero element in A[N-1,S..S+U] (or the first element with smallest\
value or any other element that suits both minimization criteria)
Reconstruct elements of the subset using matrices V and P.
时间复杂度为 O(L*N*S),其中 L 是列表的长度,N 和 S 有限制。
空间复杂度为 O(L*N*S)。