Skip to content

Commit 0e56c04

Browse files
authoredNov 19, 2024
feat: add swift implementation to lcp problem: No.51 (#3786)
1 parent d756f80 commit 0e56c04

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
 

‎lcp/LCP 51. 烹饪料理/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,46 @@ function perfectMenu(
235235
}
236236
```
237237

238+
#### Swift
239+
240+
```swift
241+
class Solution {
242+
func perfectMenu(_ materials: [Int], _ cookbooks: [[Int]], _ attribute: [[Int]], _ limit: Int) -> Int {
243+
let n = cookbooks.count
244+
var ans = -1
245+
246+
for mask in 0..<(1 << n) {
247+
var a = 0, b = 0
248+
var cnt = [Int](repeating: 0, count: 5)
249+
250+
for i in 0..<n {
251+
if (mask >> i & 1) == 1 {
252+
a += attribute[i][0]
253+
b += attribute[i][1]
254+
for j in 0..<cookbooks[i].count {
255+
cnt[j] += cookbooks[i][j]
256+
}
257+
}
258+
}
259+
260+
var ok = true
261+
for i in 0..<5 {
262+
if cnt[i] > materials[i] {
263+
ok = false
264+
break
265+
}
266+
}
267+
268+
if b >= limit && a > ans && ok {
269+
ans = a
270+
}
271+
}
272+
273+
return ans
274+
}
275+
}
276+
```
277+
238278
<!-- tabs:end -->
239279

240280
<!-- solution:end -->
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
func perfectMenu(_ materials: [Int], _ cookbooks: [[Int]], _ attribute: [[Int]], _ limit: Int) -> Int {
3+
let n = cookbooks.count
4+
var ans = -1
5+
6+
for mask in 0..<(1 << n) {
7+
var a = 0, b = 0
8+
var cnt = [Int](repeating: 0, count: 5)
9+
10+
for i in 0..<n {
11+
if (mask >> i & 1) == 1 {
12+
a += attribute[i][0]
13+
b += attribute[i][1]
14+
for j in 0..<cookbooks[i].count {
15+
cnt[j] += cookbooks[i][j]
16+
}
17+
}
18+
}
19+
20+
var ok = true
21+
for i in 0..<5 {
22+
if cnt[i] > materials[i] {
23+
ok = false
24+
break
25+
}
26+
}
27+
28+
if b >= limit && a > ans && ok {
29+
ans = a
30+
}
31+
}
32+
33+
return ans
34+
}
35+
}

0 commit comments

Comments
 (0)