, " " .
:
(+ -1 ). C (N, N div 2).
(). Multiply .
: :
FullSet = (A, B, C, D)
, A, (B, C, D) A, , A. , B ...
. .
memoization [InitialValue, Set] ( ). .
, , - , memoization.
- O (N ^ 2 * 2 ^ N), O (N * 2 ^ N), () 2 ^ N . , N <= 20 ( Int64 Count).
Delphi:
var
A: TArray<Byte>;
Memo: array of array of Int64;
N, Mask, msk, index, i: Integer;
Count: Int64;
OnlyOneOneBit: Boolean;
begin
A := TArray<Byte>.Create(1, 2, 4, 5);
N := Length(A);
Mask := (1 shl N) - 1;//binary 000111111 with n ones
SetLength(Memo, 1 shl N {2^N}, N);
for msk := 1 to Mask do begin // all possible subsets, excluding empty one
OnlyOneOneBit := 0 = (msk and (msk - 1));
for index := 0 to N - 1 do
if OnlyOneOneBit then
Memo[msk, index] := (msk shr index) and 1 // 1 if indexth bit = 1 else 0
else if 0 <> ((msk shr index) and 1) then begin
Count := 0;
for i := 0 to N - 1 do
if Abs(A[i] - A[index]) > 1 then //compatible numbers
Count := Count + Memo[msk xor (1 shl index), i];
//use previous result for the set without index element, starting with ith
Memo[msk, index] := Count;
end;
end;
Count := 0;
for index := 0 to N - 1 do
Count := Count + Memo[Mask, index];
(1, 2, 4, 5) 8
: 1425 1524 2415 2514 4152 4251 5142 5241