★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-cdzszkzo-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.git
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.github
Example:express
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,
since they don't influence the operation priority. So you should return "1000/(100/10/2)". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2
Note:數組
給定一組正整數,相鄰的整數之間將會進行浮點除法操做。例如, [2,3,4] -> 2 / 3 / 4 。微信
可是,你能夠在任意位置添加任意數目的括號,來改變算數的優先級。你須要找出怎麼添加括號,才能獲得最大的結果,而且返回相應的字符串格式的表達式。你的表達式不該該含有冗餘的括號。測試
示例:spa
輸入: [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
說明:code
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 }
12msorm
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 }