ID | Title | Difficulty | |
---|---|---|---|
Loading... |
241. Different Ways to Add Parentheses
Medium
LeetCode
Math, String, Dynamic Programming, Recursion, Memoization
Problem
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
Code
class Solution {
public List<Integer> diffWaysToCompute(String input) {
if(input == null || input.length() == 0) return new ArrayList<>();
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));
for(int l : left) {
for(int r : right){
if(c == '+'){
res.add(l + r);
} else if (c == '-') {
res.add(l - r);
} else if (c == '*') {
res.add(l * r);
}
}
}
}
}
if(res.size() == 0){
res.add(Integer.valueOf(input));
}
return res;
}
}
class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
if not input:
return []
res = []
for i in range(len(input)):
c = input[i]
if c in ['+', '-', '*']:
left = self.diffWaysToCompute(input[:i])
right = self.diffWaysToCompute(input[i + 1:])
for l in left:
for r in right:
if c == '+':
res.append(l + r)
elif c == '-':
res.append(l - r)
elif c == '*':
res.append(l * r)
if not res:
res.append(int(input))
return res
按 <- 键看上一题!
240. Search a 2D Matrix II
按 -> 键看下一题!
242. Valid Anagram