- Optimal Division
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
Notice
1.The length of the input array is [1, 10].
2.Elements in the given array will be in range [2, 1000].
3.There is only one optimal division for each test case.
思路:
想来想去觉得解就只有一个,就是x1/(x2/x3/x4…),不管xi之间关系怎么样。居然就是这么简单。
代码如下:
class Solution {
public:
/**
* @param nums: an array
* @return: the corresponding expression in string format
*/
string optimalDivision(vector<int> &nums) {
string result;
int len = nums.size();
// if (len == 0) return "";
// if (len == 1) return to_string(nums[0]);
result = result + to_string(nums[0]) + '/';
if (len > 2)
result = result + '(';
for (int i = 1; i < len; ++i) {
result = result + to_string(nums[i]) + '/';
}
result.pop_back(); //remove the last '/'
if (len > 2) result = result + ')';
return result;
}
};
本文探讨了如何从一组正整数中生成最优除法表达式的问题,通过合理添加括号改变运算优先级,以获得最大结果。文章提供了一个简洁的解决方案,并附带示例代码,展示了如何使用C++实现这一算法。
2834

被折叠的 条评论
为什么被折叠?



