题目:给定一数组,相邻的整数执行除法,但是我们可以通过添加括号改变计算的优先级,求这组数字应该如何添加括号,从而得到的结果值最大,同时结果中不应该有多余的括号,以字符串形式返回结果。例子如下:
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
假设输入的数组为a,b,c,d。现在我们通过优先级设置来寻找a/b/c/d的最大值。我们知道要想p/q最大,q必须要最小。所在,b/c/d的值要最小。我们现在的目标是如何使b/c/d的值最小。现在有两种可能:b /(c / d)跟(b / c)/ d,可以得到:
b/(c/d) (b/c)/d = b/c/d (b*d)/c b/(d*c) d/c 1/(d*c)显然d / c 大于 1 / (d * c),因为d大于1。所以我们只要保证越靠右的/的优先级最高就可以保证结果最大。代码如下:
class Solution {
public:
string intToString(int n) {
string temp;
stringstream ss;
ss << n;
ss >> temp;
return temp;
}
string optimalDivision(vector<int>& nums) {
string result = "";
if (nums.size() == 1) {
result += intToString(nums[0]);
} else if (nums.size() == 2) {
result += (intToString(nums[0]) + "/" + intToString(nums[1]));
} else {
result += (intToString(nums[0]) + "/(" + intToString(nums[1]));
for (int i = 2; i < nums.size(); i++) {
result += ("/" + intToString(nums[i]));
}
result += ")";
}
return result;
}
};