题目描述:
解法:遍历求解最小即可
class Solution {
public String minimizeResult(String expression) {
int len = expression.length();
//+位置
int mid = expression.indexOf("+");
// lL,rL分别为'('和')'的插入位置
int lL = 0, rL = len;//此处必须 rL = len,否则将下面的判断改为sum <= min
int v = Integer.valueOf(expression.substring(mid + 1, len));
int v1 = Integer.valueOf(expression.substring(0, mid));
int min = v1 + v;
for(int i = 0; i < mid; i++){
int m = Integer.valueOf(expression.substring(i, mid));//左后
int p = -1;
if(i > 0){
p = Integer.valueOf(expression.substring(0, i));//左前
}
for(int j = mid + 1; j < len; j++){
int n = -1;
if(j + 1 != len){
n = Integer.valueOf(expression.substring(j + 1, len));//右后
}
int k = Integer.valueOf(expression.substring(mid + 1, j + 1));//右前
int sum = m + k;
if(p != -1){
sum *= p;
}
if(n != -1){
sum *= n;
}
//如果 rL的初始值不是len,则此处就为 sum <= min,因为要更新最小值。
if(sum < min){
min = sum;
lL = i;
rL = j + 1;
}
}
}
StringBuilder sb = new StringBuilder(expression);
sb.insert(lL, "(");
sb.insert(rL + 1, ")");
return sb.toString();
}
}