在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4. However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximumresult, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis. Example: Input: [1000,100,10,2] Output: "1000/(100/10/2)" Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200 However, the bold parenthesis in "1000/((100/10)/2)" are redundant, Note:
给定一组正整数,相邻的整数之间将会进行浮点除法操作。例如, [2,3,4] -> 2 / 3 / 4 。 但是,你可以在任意位置添加任意数目的括号,来改变算数的优先级。你需要找出怎么添加括号,才能得到最大的结果,并且返回相应的字符串格式的表达式。你的表达式不应该含有冗余的括号。 示例: 输入: [1000,100,10,2] 输出: "1000/(100/10/2)" 解释: 1000/(100/10/2) = 1000/((100/10)/2) = 200 但是,以下加粗的括号 "1000/((100/10)/2)" 是冗余的, 因为他们并不影响操作的优先级,所以你需要返回 "1000/(100/10/2)"。 其他用例: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2 说明:
Runtime: 8 ms
Memory Usage: 18.6 MB
1 class Solution { 2 func optimalDivision(_ nums: [Int]) -> String { 3 if nums.count <= 2 { 4 return nums.map({"\($0)"}).joined(separator: "/") 5 } 6 return "\(nums.first!)" + "/(" + nums[1...].map({"\($0)"}).joined(separator: "/") + ")" 7 } 8 } 12ms 1 class Solution { 2 func optimalDivision(_ nums: [Int]) -> String { 3 var ans = nums.map { String($0) } 4 5 if nums.count < 3 { 6 return ans.joined(separator: "/") 7 } 8 9 return ans[0] + "/(" + ans[1..<ans.count].joined(separator: "/") + ")" 10 } 11 } 20ms 1 class Solution { 2 func optimalDivision(_ nums: [Int]) -> String { 3 var res:String = String() 4 var n:Int = nums.count 5 for i in 0..<n 6 { 7 if i > 0 {res += "/"} 8 if i == 1 && n > 2 {res += "("} 9 res += String(nums[i]) 10 if i == n - 1 && n > 2 {res += ")"} 11 } 12 return res 13 } 14 }
|
请发表评论