标签:diff 运算优先级 new 运算符 string inpu class hashmap parent
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
示例 1:
输入: "2-1-1"
输出: [0, 2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入: "23-45"
输出: [-34, -14, -10, -10, 10]
解释:
(2(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)5) = 10
class Solution {
private Map<String,List<Integer>> map = new HashMap<>();
public List<Integer> diffWaysToCompute(String input) {
if(map.containsKey(input))
return map.get(input);
List<Integer> res = new ArrayList<>();
for(int i = 0; i < input.length(); i++){
char c = input.charAt(i);
if(c == '+' || c == '-' || c == '*'){
List<Integer> left = diffWaysToCompute(input.substring(0,i));
List<Integer> right = diffWaysToCompute(input.substring(i + 1,input.length()));
for(int l : left){
for(int r : right){
if(c == '+'){
res.add(l + r);
}
if(c == '-'){
res.add(l - r);
}
if(c == '*'){
res.add(l * r);
}
}
}
}
}
if(res.size() == 0){
res.add(Integer.parseInt(input));
}
map.put(input,res);
return res;
}
}
标签:diff 运算优先级 new 运算符 string inpu class hashmap parent
原文地址:https://www.cnblogs.com/Tu9oh0st/p/11020477.html