1.题目
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.
给一个正整数列表,相邻数之间做浮点数除法,例如[2,3,4] 表示 2/3/4
假设可以加上任意数量的括号,求怎样加括号得到最大的结果。返回加括号后字符串形式的除法。
Example:
Input: [1000,100,10,2]
Output: “1000/(100/10/2)”
Explanation:
1000/(100/10/2) = 1000/((100/10)/2) = 200
去掉”1000/((100/10)/2)”中冗余的括号,返回结果 “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
2.分析
自己想不出来,看了solution
假设列表为[x1,x2,x3…,xn]
除法表达式为 x1/x2/x3/x4…/xn
x1始终是分子,x2始终是分母,把x3/../xn看做一个整体y
y*x1/x2 y最大为x3*x4…*xn
所以这个题目有一个通用的答案
x1/(x2/x3/…/xn)
3.代码
string optimalDivision(vector<int>& nums) {
if (nums.size() == 1)
return to_string(nums[0]);
if (nums.size() == 2)
return to_string(nums[0]) + "/" + to_string(nums[1]);
string 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;
}