【LeetCode】241. Different Ways to Add Parentheses 为运算表达式设计优先级(Medium)(JAVA)
题目地址: https://leetcode.com/problems/different-ways-to-add-parentheses/
题目描述:
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and * .
Example 1:
Input: "2-1-1"
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
题目大意
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
解题方法
- 先把所有的数字和运算符有序存到两个队列里
- 采用递归方法,对某一运算符为中心点,分割为左右两边,左右两边分别计算出所有的结果,再拼接成结果
- 循环遍历运算符,分别为不同的中心点
class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> nums = new ArrayList<>();
List<Character> operates = new ArrayList<>();
int num = 0;
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == '+' || ch == '-' || ch == '*') {
nums.add(num);
operates.add(ch);
num = 0;
} else {
num = num * 10 + ch - '0';
}
}
nums.add(num);
return dH(nums, operates, 0, operates.size());
}
public List<Integer> dH(List<Integer> nums, List<Character> operates, int start, int end) {
List<Integer> res = new ArrayList<>();
for (int i = start; i < end; i++) {
char operate = operates.get(i);
List<Integer> left = dH(nums, operates, start, i);
List<Integer> right = dH(nums, operates, i + 1, end);
for (int j = 0; j < left.size(); j++) {
for (int k = 0; k < right.size(); k++) {
res.add(getResult(left.get(j), right.get(k), operate));
}
}
}
if (start == end) res.add(nums.get(start));
return res;
}
public int getResult(int pre, int cur, char operate) {
if (operate == '+') return pre + cur;
if (operate == '-') return pre - cur;
return pre * cur;
}
}
执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:38.8 MB,击败了28.06% 的Java用户