在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There are G people in a gang, and a list of various crimes they could commit. The 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 How many schemes can be chosen? Since the answer may be very large, return it modulo Example 1: Input: G = [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 = [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:
帮派里有 G 名成员,他们可能犯下各种各样的罪行。 第 让我们把这些犯罪的任何子集称为盈利计划,该计划至少产生 有多少种方案可以选择?因为答案很大,所以返回它模 示例 1: 输入:G = 5, P = 3, group = [2,2], profit = [2,3] 输出:2 解释: 至少产生 3 的利润,该帮派可以犯下罪 0 和罪 1 ,或仅犯下罪 1 。 总的来说,有两种方案。 示例 2: 输入:G = 10, P = 5, group = [2,3,5], profit = [6,7,8] 输出:7 解释: 至少产生 5 的利润,只要他们犯其中一种罪就行,所以该帮派可以犯下任何罪行 。 有 7 种可能的计划:(0),(1),(2),(0,1),(0,2),(1,2),以及 (0,1,2) 。 提示:
Runtime: 1032 ms
Memory Usage: 18.8 MB
1 class Solution { 2 func profitableSchemes(_ G: Int, _ P: Int, _ group: [Int], _ profit: [Int]) -> Int { 3 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:G + 1),count:P + 1) 4 dp[0][0] = 1 5 var res:Int = 0 6 var mod:Int = Int(1e9 + 7) 7 for k in 0..<group.count 8 { 9 var g:Int = group[k] 10 var p:Int = profit[k] 11 for i in stride(from:P,through:0,by:-1) 12 { 13 for j in stride(from:G - g,through:0,by:-1) 14 { 15 dp[min(i + p, P)][j + g] = (dp[min(i + p, P)][j + g] + dp[i][j]) % mod 16 } 17 } 18 } 19 for x in dp[P] 20 { 21 res = (res + x) % mod 22 } 23 return res 24 } 25 } Runtime: 1192 ms
Memory Usage: 19.4 MB
1 class Solution { 2 func profitableSchemes(_ G: Int, _ P: Int, _ group: [Int], _ profit: [Int]) -> Int { 3 guard G >= 1 && G <= 100 && P >= 0 && P <= 100 && group.count >= 1 && group.count <= 100 && group.count == profit.count else { 4 return 0 5 } 6 let mod = Int(1e9 + 7) 7 var crimePlanCount = Array(repeating: Array(repeating: 0, count: G + 1), count: P + 1) 8 crimePlanCount[0][0] = 1 9 for (index, groupValue) in group.enumerated() { 10 let profitValue = profit[index] 11 for p in stride(from: P, through: 0, by: -1) { 12 for g in stride(from: G, through: 0, by: -1) { 13 if groupValue + g > G || crimePlanCount[p][g] == 0 { 14 continue 15 } 16 let targetProfit = min(P, profitValue + p) 17 let targetGroup = groupValue + g 18 crimePlanCount[targetProfit][targetGroup] += crimePlanCount[p][g] 19 crimePlanCount[targetProfit][targetGroup] %= mod 20 } 21 } 22 } 23 var result = 0 24 for count in crimePlanCount[P] { 25 result += count 26 } 27 return result % mod 28 } 29 }
|
请发表评论