553. Optimal Division
来源:互联网 发布:win10网络图标不能运行 编辑:程序博客网 时间:2024/06/05 07:05
题目
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 maximum result, 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,
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:
- The length of the input array is [1, 10].
- Elements in the given array will be in range [2, 1000].
- There is only one optimal division for each test case.
思路
这道题目,给你一个数组,里面都是正整数,默认相邻整数之间做整除运算”/“。你可以给这些算式添加括号,但不能重复添加,或者添加不必要的括号。使得你添加括号后这个算式的结果最大。这道题目把许多人难住了,包括我。我拿到这个题目,第一个想法是,我应该从上述式子中找规律。我猜想这个式子应该满足某种规律从而使得添加括号后数值最大。但是不幸的是,在我看了没10秒钟,我突然有种强烈的感觉,这道题目应该用动态规划来做,于是在dp的路上越走越远。。。其实大家如果多花点时间观察算式,就能发现,无论如何,算式
代码
class Solution {public: string optimalDivision(vector<int>& nums) { string res; if(nums.size()==0) return res; else if(nums.size()==1) { res = to_string(nums[0]); return res; } else if(nums.size()==2) res = to_string(nums[0])+"/"+to_string(nums[1]); else { res = to_string(nums[0])+"/("+to_string(nums[1]); for(int i=2;i<nums.size();i++) res+= "/"+to_string(nums[i]); res+=")"; } return res; }};
- leetcode 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- leetcode 553. Optimal Division
- 553. Optimal Division
- LeetCode:553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- leetcode 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- [leetcode]553. Optimal Division
- [LeetCode]553. Optimal Division
- LeetCode:553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553. Optimal Division
- 553.Optimal Division
- windows桌面便笺使用小技巧
- ubuntu1404 MTD安装 ubi文件系统制作
- Unity 全局游戏脚本的一种实现方法
- iOS之强大的sscanf
- [Leetcode] 501. Find Mode in Binary Search Tree 解题报告
- 553. Optimal Division
- B+/-Tree原理及mysql的索引分析
- RPM强制安装
- Java多态
- Kaggle Titanic 模型优化提升第三弹
- 欢迎使用CSDN-markdown编辑器
- Centos搭建ceph+++七、准备OSD
- web.xml文件详解
- xposed 5.0以上资源地址