我正在浏览leetcode的一些文章。以下是其中一个https://leetcode.com/articles/optimal-division/。
给定正整数列表,相邻的整数将执行浮点除法。例如,[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
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
我认为解决方案的时间复杂度是O(N ^ 2)不是吗?
这是备忘录解决方案
public class Solution {
class T {
float max_val, min_val;
String min_str, max_str;
}
public String optimalDivision(int[] nums) {
T[][] memo = new T[nums.length][nums.length];
T t = optimal(nums, 0, nums.length - 1, "", memo);
return t.max_str;
}
public T optimal(int[] nums, int start, int end, String res, T[][] memo) {
if (memo[start][end] != null)
return memo[start][end];
T t = new T();
if (start == end) {
t.max_val = nums[start];
t.min_val = nums[start];
t.min_str = "" + nums[start];
t.max_str = "" + nums[start];
memo[start][end] = t;
return t;
}
t.min_val = Float.MAX_VALUE;
t.max_val = Float.MIN_VALUE;
t.min_str = t.max_str = "";
for (int i = start; i < end; i++) {
T left = optimal(nums, start, i, "", memo);
T right = optimal(nums, i + 1, end, "", memo);
if (t.min_val > left.min_val / right.max_val) {
t.min_val = left.min_val / right.max_val;
t.min_str = left.min_str + "/" + (i + 1 != end ? "(" : "") + right.max_str + (i + 1 != end ? ")" : "");
}
if (t.max_val < left.max_val / right.min_val) {
t.max_val = left.max_val / right.min_val;
t.max_str = left.max_str + "/" + (i + 1 != end ? "(" : "") + right.min_str + (i + 1 != end ? ")" : "");
}
}
memo[start][end] = t;
return t;
}
}