[Swift Weekly Contest 114]LeetCode956. 最高的廣告牌 | Tallest Billboard
阿新 • • 發佈:2018-12-09
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You have a collection of rods
which can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.
Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.
Example 1:
Input: [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
Example 2:
Input: [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
Example 3:
Input: [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.
Note:
0 <= rods.length <= 20
1 <= rods[i] <= 1000
The sum of rods is at most 5000.
你正在安裝一個廣告牌,並希望它高度最大。這塊廣告牌將有兩個鋼製支架,兩邊各一個。每個鋼支架的高度必須相等。
你有一堆可以焊接在一起的鋼筋 rods
。舉個例子,如果鋼筋的長度為 1、2 和 3,則可以將它們焊接在一起形成長度為 6 的支架。
返回廣告牌的最大可能安裝高度。如果沒法安裝廣告牌,請返回 0。
示例 1:
輸入:[1,2,3,6] 輸出:6 解釋:我們有兩個不相交的子集 {1,2,3} 和 {6},它們具有相同的和 sum = 6。
示例 2:
輸入:[1,2,3,4,5,6] 輸出:10 解釋:我們有兩個不相交的子集 {2,3,5} 和 {4,6},它們具有相同的和 sum = 10。
示例 3:
輸入:[1,2] 輸出:0 解釋:沒法安裝廣告牌,所以返回 0。
提示:
0 <= rods.length <= 20
1 <= rods[i] <= 1000
鋼筋的總數最多為 5000 根
1396ms
1 class Solution { 2 func tallestBillboard(_ rods: [Int]) -> Int { 3 var n:Int = rods.count 4 var h:Int = n/2 5 var o:Int = 10002 6 var ls:[Int] = [Int](repeating:-99999999,count:20005) 7 for i in 0..<Int(pow(3, Double(h))) 8 { 9 var s:Int = 0 10 var ass:Int = 0 11 var v:Int = i 12 for j in 0..<h 13 { 14 var w:Int = v % 3 15 if w == 1 16 { 17 18 } 19 else if w == 0 20 { 21 s += rods[j] 22 ass += rods[j] 23 } 24 else 25 { 26 s -= rods[j] 27 ass += rods[j] 28 } 29 v /= 3 30 } 31 ls[s+o] = max(ls[s+o], ass) 32 } 33 var ret:Int = 0 34 for i in 0..<Int(pow(3, Double(n - h))) 35 { 36 var s:Int = 0 37 var ass:Int = 0 38 var v:Int = i 39 for j in 0..<(n - h) 40 { 41 var w:Int = v % 3 42 if w == 1 43 { 44 45 } 46 else if w == 0 47 { 48 s += rods[j + h] 49 ass += rods[j + h] 50 } 51 else 52 { 53 s -= rods[j + h] 54 ass += rods[j + h] 55 } 56 v /= 3 57 } 58 ret = max(ret, (ls[o-s] + ass) / 2) 59 } 60 return ret 61 } 62 }