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.
刚开始想是动态规划,但后来发现此题有规律可循,即将第一个数后面的括起来意味着解除括号后后面的都是相乘的,所以直接后面开始加括号就可以求得最大解:
class Solution {
public:
string optimalDivision(vector<int>& nums) {
string ans;
if(!nums.size()) return ans;
ans = to_string(nums[0]);
if(nums.size()==1) return ans;
if(nums.size()==2) return ans + "/" + to_string(nums[1]);
ans += "/(" + to_string(nums[1]);
for(int i = 2; i < nums.size();++i)
ans += "/" + to_string(nums[i]);
ans += ")";
return ans;
}
};
而此题按动态规划思路来解的话参考网友答案。。。未完待续
此题是亚马逊面试题,而禁止用简单方法:
public class Solution {
public String optimalDivision(int[] nums) {
Map<String, pair> memory = new HashMap<>();
pair sol = divid(nums,0,nums.length-1, memory);
return sol.maxS;
}
public pair divid(int[] nums, int start, int end, Map<String, pair> memory){
String key = start + " " + end;
if(memory.containsKey(key)) return memory.get(key);
if(start == end) return new pair(nums[start], "" + nums[start],nums[start], "" + nums[start]);
pair sol = new pair(0,"",0,"");
for(int i = start; i < end; i++){
pair left = divid(nums, start, i, memory);
pair right = divid(nums, i + 1, end, memory);
double min = left.min / right.max;
String minS = left.minS + "/" + (i + 1 == end ? right.maxS : "(" + right.maxS + ")");
double max = left.max / right.min;
String maxS = left.maxS + "/" + (i + 1 == end ? right.minS : "(" + right.minS + ")");
if(sol.min == 0 || min < sol.min){
sol.min = min;
sol.minS = minS;
}
if(max > sol.max){
sol.max = max;
sol.maxS = maxS;
}
}
memory.put(key, sol);
return sol;
}
}
class pair{
double min;
String minS;
double max;
String maxS;
public pair(double min, String minS, double max, String maxS){
this.min = min;
this.minS = minS;
this.max = max;
this.maxS = maxS;
}
}