码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-25双周赛-5387-每个人戴不同帽子的方案数*

时间:2020-05-03 21:35:02      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:cto   https   记忆化   each   class   src   end   联系   dex   

题目描述:

技术图片

 

 技术图片

 

 方法一:记忆化递归+状态压缩 *

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-每个人戴不同帽子的方案数*

标签:cto   https   记忆化   each   class   src   end   联系   dex   

原文地址:https://www.cnblogs.com/oldby/p/12823383.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!