dp
with dimensions [1 << n][n]
and set all values to 0.dp[1 << i][i]
to 1 for all i
from 0 to n-1
, representing the starting point of permutations.mask
from 1 to (1 << n) - 1
.mask
, iterate over all indices i
such that nums[i]
is included in mask
.i
, iterate over all indices j
such that nums[j]
is not included in mask
.nums[j]
is divisible by nums[i]
or vice versa, update dp[new_mask][j]
where new_mask
is mask
with the j-th bit set.dp[(1 << n) - 1][i]
for all i
.