LC每日一题|20240626 - 2741. 特别的排列

71 阅读1分钟

LC每日一题|20240626 - 2741. 特别的排列

给你一个下标从 0 开始的整数数组 nums ,它包含 n 个 互不相同 的正整数。如果 nums 的一个排列满足以下条件,我们称它是一个特别的排列:

  • 对于 0 <= i < n - 1 的下标 i ,要么 nums[i] % nums[i+1] == 0 ,要么 nums[i+1] % nums[i] == 0 。

请你返回特别排列的总数目,由于答案可能很大,请将它对 ****109 + 7 取余 后返回。

提示:

  • 2 <= nums.length <= 14
  • 1 <= nums[i] <= 10^9

题目等级:Medium

解题思路

状压dp,目前还没看懂

AC代码

class Solution {
    fun specialPerm(nums: IntArray): Int {
        val mem = Array<LongArray>((1 shl nums.size) - 1) { LongArray(nums.size) { -1L } }
        var ans = 0L
        for (i in nums.indices) {
            ans += dfs(mem.size xor (1 shl i), i, nums, mem)
        }
        return (ans % 1_000_000_007).toInt()
    }

    fun dfs(s: Int, i: Int, nums: IntArray, mem: Array<LongArray>) : Long {
        if (s == 0) return 1L
        if (mem[s][i] != -1L) return mem[s][i]
        var res = 0L
        for (j in nums.indices) {
            if ((s shr j) and 1 > 0 && (nums[i] % nums[j] == 0 || nums[j] % nums[i] == 0)) {
                res += dfs(s xor (1 shl j), j, nums, mem)
            }
        }
        mem[s][i] = res
        return res
    }
}