【LeetCode 879】 Profitable Schemes

题目描述

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 1:

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.

Example 2:

Input: G = 10, P = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation: 
To make a profit of at least 5, the gang could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).

Note:

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

思路

01背包变形 。 要求把物品放进一定容量的背包里,每个物品有固定价值和容量。求最后背包价值大于等于P的方案数。
动态规划,一件一件放,dp[k][i][j]表示前k件物品安排完放不放以后,价值 ≥ i,容量为j的方案数。
dp[k][i][j] += dp[k-1][i][j] + dp[k-1][i-profit[k-1]][j-group[k-1]]
那么对于第k件物品,可以选择放和不放。放的前提条件是,容量还够。对于i-profit[k-1]<0的情况,说明放上第k件物品之后,价值>i,符合利益≥i 的的条件,方案数记录在 dp[k-1][0][j-group[k-1]]里。
还是挺绕的。

代码

class Solution {
public:
    int profitableSchemes(int G, int P, vector<int>& group, vector<int>& profit) {
        int K = group.size();
        vector<vector<vector<int>>> dp(K+1, vector<vector<int>>(P+1, vector<int>(G+1)));
        
        int MOD = 1e9+7;
        
        dp[0][0][0] = 1; // task profit persons
        
        for (int k=1; k<=K; ++k) {
            int curp = profit[k-1], curg = group[k-1];
            for (int p=0; p<=P; ++p) {
                for (int g=0; g<=G; ++g) {
                    dp[k][p][g] += dp[k-1][p][g] + (g>=curg ? dp[k-1][(p-curp>=0 ? p-curp : 0)][g-curg] : 0);
                    dp[k][p][g] %= MOD;
                }
            }
        }
        
        int res = 0;
        for (int i=0; i<=G; ++i) {
            res += dp[K][P][i];
            res %= MOD;
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值