feat: add swift implementation to lcp problem: No.51 (#3786)

This commit is contained in:
Lanre Adedara 2024-11-19 12:14:39 +01:00 committed by GitHub
parent d756f80f9e
commit 0e56c04098
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 75 additions and 0 deletions

View File

@ -235,6 +235,46 @@ function perfectMenu(
}
```
#### Swift
```swift
class Solution {
func perfectMenu(_ materials: [Int], _ cookbooks: [[Int]], _ attribute: [[Int]], _ limit: Int) -> Int {
let n = cookbooks.count
var ans = -1
for mask in 0..<(1 << n) {
var a = 0, b = 0
var cnt = [Int](repeating: 0, count: 5)
for i in 0..<n {
if (mask >> i & 1) == 1 {
a += attribute[i][0]
b += attribute[i][1]
for j in 0..<cookbooks[i].count {
cnt[j] += cookbooks[i][j]
}
}
}
var ok = true
for i in 0..<5 {
if cnt[i] > materials[i] {
ok = false
break
}
}
if b >= limit && a > ans && ok {
ans = a
}
}
return ans
}
}
```
<!-- tabs:end -->
<!-- solution:end -->

View File

@ -0,0 +1,35 @@
class Solution {
func perfectMenu(_ materials: [Int], _ cookbooks: [[Int]], _ attribute: [[Int]], _ limit: Int) -> Int {
let n = cookbooks.count
var ans = -1
for mask in 0..<(1 << n) {
var a = 0, b = 0
var cnt = [Int](repeating: 0, count: 5)
for i in 0..<n {
if (mask >> i & 1) == 1 {
a += attribute[i][0]
b += attribute[i][1]
for j in 0..<cookbooks[i].count {
cnt[j] += cookbooks[i][j]
}
}
}
var ok = true
for i in 0..<5 {
if cnt[i] > materials[i] {
ok = false
break
}
}
if b >= limit && a > ans && ok {
ans = a
}
}
return ans
}
}