Optimal Division In Array

题目描述:Optimal Division In Array(数组中除法的最优切分)

给定一个数组[x1,x2,x3….xn]。我们定义其为连除模式,即x1/x2/x3/x4..xn。在这个序列中我们可以在任意位置中加上括号改变其计算顺序。要求找到其中所有加入括号的结果中最大的那个加入括号的方式,并返回加入括号所形成的字符串。

例子:

[1000,100,10,2],我们可以加入括号形成(1000/100)/(10/2),或者1000/(100/(10/2))等。详细解释可以看 leetcode

解题思路:

初看这个题目会觉得非常的难,因为需要考虑到所有的情况中最大的那一种;并且需要在不同的位置上加上括号形成字符串。但是其实仔细考虑后我们就会发下:即不管在任意位置上加上括号,x1永远是除数,而x2永远中是被除数中的一个。所以我们就可以写成等价的方式x1/(x2/y),其中y的方式可以是任意的。通过调整分子分母可以发现:x1/(x2/y) = x1y/(x2).所以最大值的情况在y最大的情况下出现,而y的最大化即为(x3 x4 * x5….)。所以最后的最大结果肯定是:x1/(x2/(x3/x4/x5….xn)),所以我们直接返回这样的结果即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
string optimalDivision(vector<int>& nums) {
int n = nums.size();
if (n == 0) return "";
if (n == 1) return to_string(nums[0]);
if (n == 2) return to_string(nums[0]) + "/" + to_string(nums[1]);
//分别判断数组长度只有0,1,2的情况
string res;
res = res + to_string(nums[0]) + "/(" + to_string(nums[1]);
for (int i = 2; i < nums.size(); i++){
res = res + "/" + to_string(nums[i]);
}
res = res + ")";
//构造所需要的字符串即可
return res;
}
};