LC状态dp经典题--特别的排列
作者:
hayabusa
,
2024-06-26 17:51:38
,
所有人可见
,
阅读 7
https://leetcode.cn/problems/special-permutations/description/?envType=daily-question&envId=2024-06-26
class Solution {
public:
int mod = 1e9 + 7;
int n;
int specialPerm(vector<int>& nums) {
vector<vector<int>> dp(1 << 14, vector<int>(15, 0));
n = nums.size();
for (int i = 0; i < n; i++) {
dp[1 << i][i] = 1;
}
for (int i = 1; i < 1 << n; i ++) {
for (int j = 0; j < n; j++) {
if ((i >> j &1) == 0) continue;
int t = i;
for (int k = 0; k < n; k++) {
if( k == j || (i >> k & 1) == 0) continue;
if ( (nums[k] % nums[j] == 0 || nums[j] % nums[k] == 0 )) {
dp[i][j] = (dp[i][j] + dp[t - (1 << j)][k]) % mod;
}
}
}
}
long long res = 0;
for (int i = 0; i < n; i++) res = (res + dp[(1 << n) -1][i] )% mod;
return res;
}
};