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 }

使用分治的思想。

 
posted @ 2016-06-27 13:35  Miller1991  阅读(138)  评论(0编辑  收藏  举报