zoukankan      html  css  js  c++  java
  • Leetcode: 879. Profitable Schemes

    Description

    There are G people in a gang, and a list of various crimes they could commit.
    
    The i-th crime generates a profit[i] and requires group[i] gang members to participate.
    
    If a gang member participates in one crime, that member can't participate in another crime.
    
    Let's call a profitable scheme any subset of these crimes that generates at least P profit, and the total number of gang members participating in that subset of crimes is at most G.
    
    How many schemes can be chosen?  Since the answer may be very large, return it modulo 10^9 + 7.
    

    Example

    Input: G = 5, P = 3, group = [2,2], profit = [2,3]
    Output: 2
    Explanation: 
    To make a profit of at least 3, the gang could either commit crimes 0 and 1, or just crime 1.
    In total, there are 2 schemes.
    

    Note

    1 <= G <= 100
    0 <= P <= 100
    1 <= group[i] <= 100
    0 <= profit[i] <= 100
    1 <= group.length = profit.length <= 100
    

    分析

        这道题目虽然是 hard 级别,但是比一般 medium 级别题目要简单。就是一般的 二维 dp,即 dp[g][p]. 关键的优化点是  在 p 大于等于 P 时,不在细分 p 
    

    code

        def profitableSchemes(self, G, P, g, p):
            """
            :type G: int
            :type P: int
            :type group: List[int]
            :type profit: List[int]
            :rtype: int
            """
            dp = [[0 for _ in range(P+1)] for _ in range(G+1)]
    
            for i, _ in enumerate(p):
                if g[i] > G:
                    continue
                for j in range(G, g[i]-1, -1):
                    if p[i] >= P:
                        dp[j][P] += sum(dp[j-g[i]])
                    else:
                        dp[j][P] += sum(dp[j-g[i]][P-p[i]:])
                    for k in range(p[i], P):
                        dp[j][k] += dp[j-g[i]][k-p[i]]
    
                if p[i] >= P:
                    dp[g[i]][P] += 1
                else:
                    dp[g[i]][p[i]] += 1
    
            return sum([d[P] for d in dp])%1000000007
        
    
    

    总结

    Runtime: 668 ms, faster than 100.00% of Python online submissions for Profitable Schemes.
    Memory Usage: 13.1 MB, less than 75.00% of Python online submissions for Profitable Schemes.
    Next challenges:
    
  • 相关阅读:
    JS 中 new 操作符
    js清除浏览器缓存的几种方法
    一个自定义分享按钮
    解决windows下nginx中文文件名乱码
    sublime text 3 添加 javascript 代码片段 ( snippet )
    transition动画最简使用方式
    hammerjs jquery的选项使用方法,以给swipe设置threshold和velocity为例
    sublime text 3 的emmet 添加自定义 html 片段
    解决 placeholder 垂直不居中,偏上的问题
    Sublime Text 3 配置 sass
  • 原文地址:https://www.cnblogs.com/tmortred/p/13234434.html
Copyright © 2011-2022 走看看