[LeetCode] 241. 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"
.
((2-1)-1) = 0 (2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(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
Output: [-34, -14, -10, -10, 10]
给定一个含有数字和运算符的表达式,运算符可以是加减乘,在任意位置添加括号,求出所有可能的表达式值。
解法:递归
Java:
public class Solution { public List<Integer> diffWaysToCompute(String input) { List<Integer> result = new ArrayList<>(); if (input == null || input.length() == 0) { return result; } for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (!isOperator(c)) { continue; } List<Integer> left = diffWaysToCompute(input.substring(0, i)); List<Integer> right = diffWaysToCompute(input.substring(i + 1)); for (int num1 : left) { for (int num2 : right) { int val = calculate(num1, num2, c); result.add(val); } } } // only contains one number if (result.isEmpty()) { result.add(Integer.parseInt(input)); } return result; } private int calculate(int num1, int num2, char operator) { int result = 0; switch(operator) { case '+' : result = num1 + num2; break; case '-' : result = num1 - num2; break; case '*' : result = num1 * num2; break; } return result; } private boolean isOperator(char operator) { return (operator == '+') || (operator == '-') || (operator == '*'); } }
Python:
import operator import re class Solution: # @param {string} input # @return {integer[]} def diffWaysToCompute(self, input): tokens = re.split('(\D)', input) nums = map(int, tokens[::2]) ops = map({'+': operator.add, '-': operator.sub, '*': operator.mul}.get, tokens[1::2]) lookup = [[None for _ in xrange(len(nums))] for _ in xrange(len(nums))] def diffWaysToComputeRecu(left, right): if left == right: return [nums[left]] if lookup[left][right]: return lookup[left][right] lookup[left][right] = [ops[i](x, y) for i in xrange(left, right) for x in diffWaysToComputeRecu(left, i) for y in diffWaysToComputeRecu(i + 1, right)] return lookup[left][right] return diffWaysToComputeRecu(0, len(nums) - 1)
Python:
class Solution: # @param {string} input # @return {integer[]} def diffWaysToCompute(self, input): lookup = [[None for _ in xrange(len(input) + 1)] for _ in xrange(len(input) + 1)] ops = {'+': operator.add, '-': operator.sub, '*': operator.mul} def diffWaysToComputeRecu(left, right): if lookup[left][right]: return lookup[left][right] result = [] for i in xrange(left, right): if input[i] in ops: for x in diffWaysToComputeRecu(left, i): for y in diffWaysToComputeRecu(i + 1, right): result.append(ops[input[i]](x, y)) if not result: result = [int(input[left:right])] lookup[left][right] = result return lookup[left][right] return diffWaysToComputeRecu(0, len(input))
C++:
class Solution { public: vector<int> diffWaysToCompute(string input) { vector<int> res; for (int i = 0; i < input.size(); ++i) { if (input[i] == '+' || input[i] == '-' || input[i] == '*') { vector<int> left = diffWaysToCompute(input.substr(0, i)); vector<int> right = diffWaysToCompute(input.substr(i + 1)); for (int j = 0; j < left.size(); ++j) { for (int k = 0; k < right.size(); ++k) { if (input[i] == '+') res.push_back(left[j] + right[k]); else if (input[i] == '-') res.push_back(left[j] - right[k]); else res.push_back(left[j] * right[k]); } } } } if (res.empty()) res.push_back(atoi(input.c_str())); return res; } };
类似题目:
[LeetCode] 95. Unique Binary Search Trees II 唯一二叉搜索树 II