题目描述
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
示例:
输入: “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
Sample Code
分治算法,备忘录优化
class Solution {
HashMap<String, List<Integer>> map = new HashMap<>();
public List<Integer> diffWaysToCompute(String input) {
if(map.containsKey(input)) return map.get(input);
List<Integer> list = new ArrayList<>();
for(int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if(c == '+' || c == '-' || c == '*') {
List<Integer> le = diffWaysToCompute(input.substring(0, i));
List<Integer> ri = diffWaysToCompute(input.substring(i+1));
for(int l : le) {
for(int r : ri) {
switch(c) {
case '+':
list.add(l + r);
break;
case '-':
list.add(l - r);
break;
case '*':
list.add(l * r);
break;
}
}
}
}
}
if(list.size() == 0) list.add(Integer.parseInt(input));
map.put(input, list);
return list;
}
}
ERROR Code
应该先转换成数组就要方便一些了,回溯,注意一下边界
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> diffWaysToCompute(String input) {
int nums = 1;
for(int i = 0; i < input.length(); i++)
if(!Character.isDigit(input.charAt(i))) nums++;
helper(input, nums);
return res;
}
private void helper(String input, int nums) {
if(nums == 1) {
res.add(Integer.parseInt(input));
return;
}
for(int i = 0; i < input.length(); ) {
String start = input.substring(0, i);
int x = 0;
while(Character.isDigit(input.charAt(i))) {
// x = x*10 + Integer.parseInt(input.charAt(i));
x = x*10 + (input.charAt(i)-'0');
i++;
}
char c = input.charAt(i);
int j = i+1;
int y = 0;
while(Character.isDigit(input.charAt(j))) {
y = y*10 + (input.charAt(i)-'0');
j++;
}
String temp = cal(x, y, c);
helper(start+temp+input.substring(j), nums-1);
}
}
private String cal(int x, int y, char c) {
switch(c) {
case '+':
return (String) "" + (x + y);
case '-':
return (String) "" + (x - y);
case '*':
return (String) "" + (x * y);
}
return null;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/different-ways-to-add-parentheses