これは、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) です。