241. Different Ways to Add Parentheses java solutions

Posted Miller1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了241. Different Ways to Add Parentheses java solutions相关的知识,希望对你有一定的参考价值。

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]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

 1 public class Solution {
 2     public List<Integer> diffWaysToCompute(String input) {
 3         List<Integer> ans = new ArrayList<Integer>();
 4         for(int i = 0; i < input.length(); i++){
 5             char c = input.charAt(i);
 6             if(c != ‘+‘ && c != ‘-‘ && c != ‘*‘) continue;
 7             List<Integer> left = diffWaysToCompute(input.substring(0,i));
 8             List<Integer> right = diffWaysToCompute(input.substring(i+1,input.length()));
 9             for(int le : left){
10                 for(int ri : right){
11                     if(c == ‘+‘) ans.add(le+ri);
12                     else if(c == ‘-‘) ans.add(le-ri);
13                     else if(c == ‘*‘) ans.add(le*ri);
14                 }
15             }
16         }
17         if(ans.size() == 0) ans.add(Integer.parseInt(input));
18         return ans;
19     }
20 }

使用分治的思想。

 

以上是关于241. Different Ways to Add Parentheses java solutions的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode241. Different Ways to Add Parentheses

241. Different Ways to Add Parentheses

LeetCode 241. Different Ways to Add Parentheses

241. Different Ways to Add Parentheses

241. Different Ways to Add Parentheses

leetcode 241. Different Ways to Add Parentheses