原题链接:https://leetcode.cn/problems/special-permutations/
本题是一个状态压缩dp
一开始尝试用普通的dp去做,但是超时了
func specialPerm(nums []int) int {
visited := make(map[int]bool)
return dfs(nums, visited, 0, 0)
}
func dfs(nums []int, visited map[int]bool, idx, lastNum int) int {
res := 0
mod := int(math.Pow(10, 9) + 7)
n := len(nums)
if idx >= n {
return 1
}
for j := 0; j < n; j ++ {
if value, ok := visited[nums[j]]; ok && value {
continue
}
currNum := nums[j]
if idx == 0 || currNum % lastNum == 0 || lastNum % currNum == 0 {
visited[currNum] = true
res = (res + dfs(nums, visited, idx + 1, currNum)) % mod
visited[currNum] = false
}
}
return res
}
后来看了题解之后,进行了优化,使用状态压缩dp
func specialPerm(nums []int) int {
n := len(nums)
// all numbers
m := (1 << n)
memo := make([][]int, m)
for i := range memo {
memo[i] = make([]int, n)
for j := 0; j < n; j ++ {
memo[i][j] = -1
}
}
const mod int = 1e9+7
var dfs func(int, int) int
dfs = func(mask, k int) int {
// 已经全部选完,返回一个有效的排列
if mask == 0 {
return 1
}
if memo[mask][k] != -1 {
return memo[mask][k]
}
res := 0
for i, num := range nums {
// select one that have not chosen and satisfy the condition
if (mask >> i) & 1 == 1 && (num % nums[k] == 0 || nums[k] % num == 0) {
res = (res + dfs(mask ^ (1 << i), i)) % mod
}
}
memo[mask][k] = res
return res
}
res := 0
for i := range nums {
res = (res + dfs((m - 1) ^ (1 << i), i)) % mod
}
return res
}
其实区别在于使用状态压缩dp,可以进行记忆化搜索,来节省时间复杂度