原题链接:https://leetcode.com/problems/different-ways-to-add-parentheses/
1. 题目介绍
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
2. 解题思路
递归法
这个题可以使用递归,逐步求解子问题。和 95. Unique Binary Search Trees II 的解题思路很类似。
按照符号的不同位置,我们可以将字符串分为三个部分,中间是操作符,左边和右边都是子串。比如:
Input: "2*3-4*5"
可以分为:
2 * (3-4*5) 或者 (2*3) - (4*5) 或者 (2*3-4) * 5
这样,一个字符串的结果集,就是每一个左子串的结果和每一个右子串的结果进行运算的集合。我们使用这种方法逐层求解,最终可以计算出全部的结果。
需要注意的是,这个题目中允许结果集中有重复的元素。
实现代码
class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> ans = new ArrayList<>();
int N = input.length();
if(N == 0){
return ans;
}
for(int i = 0 ; i < N ; i++){
char x = input.charAt(i);
if(x == '+' || x == '*' || x == '-'){
List<Integer> left = diffWaysToCompute(input.substring( 0 ,i));
List<Integer> right = diffWaysToCompute(input.substring(i+1,N));
for(int j : left){
for(int k : right){
int temp = 0;
if(x == '+'){ temp = j + k; }
else if(x == '*'){ temp = j * k; }
else if(x == '-'){ temp = j - k; }
ans.add(temp);
}
}
}
}
//针对没有运算符号只有数字的情况,这个数字可能只有一位,也可能是有多位
if(ans.isEmpty() == true){
ans.add( Integer.parseInt(input) );
}
return ans;
}
}