leetcode-25双周赛-5387-每个人戴不同帽子的方案数*
Posted 真不知道叫啥好
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-25双周赛-5387-每个人戴不同帽子的方案数*相关的知识,希望对你有一定的参考价值。
题目描述:
方法一:记忆化递归+状态压缩 *
from functools import lru_cache class Solution: def numberWays(self, hats: List[List[int]]) -> int: N = len(hats) M = 41 mod = 10 ** 9 + 7 hatsLookup = [] for personHats in hats: hatsLookup.append(set(personHats)) @lru_cache(None) def go(index, mask): if index == M: if mask == (1 << N) - 1: return 1 return 0 count = 0 for x in range(N): if index in hatsLookup[x] and (mask & (1 << x)) == 0: count += go(index + 1, mask | (1 << x)) count %= mod count += go(index + 1, mask) return count % mod return go(0, 0) % mod
方法二:01背包dp
class Solution: def numberWays(self, hats): n, mod = len(hats), 10**9+7 h2p = {} for i in range(n): for j in hats[i]: h2p[j] = h2p.get(j, []) + [i] target = (1 << n) -1 dp = [0] * (target+1) dp[0] = 1 for hat in h2p: for i in range(target, -1, -1): for p in h2p[hat]: if i&(1<<p): dp[i] += dp[i-(1<<p)] dp[i] %= mod return dp[-1]%mod 作者:dangerusswilson 链接:https://leetcode-cn.com/problems/number-of-ways-to-wear-different-hats-to-each-other/solution/python-01bei-bao-by-dangerusswilson/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
以上是关于leetcode-25双周赛-5387-每个人戴不同帽子的方案数*的主要内容,如果未能解决你的问题,请参考以下文章
[E差分] lc1893. 检查是否区域内所有整数都被覆盖(差分计数+模拟+双周赛54_1)