If you are given the set L={1,2,3,...,N} and an integer k, is it possible to efficiently calculate the number of “non-adjacent” subsets of size k? A subset S is non-adjacent if for each x in S, neither x-1 nor x+1 are in S.
As an example, for L={1,2,3,4} and k=2 the answer is 3, because we have
{1,3},{1,4},{2,4}. For k=3 the answer is zero.
One way to go would be to generate all size 2 non-adjacent subsets, then trying all possible unions (since a non-adjacent set has the property that all its subsets are non-adjacent), but that strikes me as very wasteful, and probably there is a sweet elegant efficient solution.
Denote by
S(m,n)the number of non-adjacent subsets of sizemin{1,...,n}. Then the following holds:So one can solve it by DP in
O(Nk), by adding the boundary conditionswhere
I()is the indicator function.