Different Ways to Add Parentheses 对表达式添加括号,能有几种不同答案
对表达式添加括号,能有几种不同答案
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]
这题可以换个思路考虑, 其实在每个数字和符号之间都可以添加括号, 而且题目没有要求符号的数量. 这个其实就是在问, 有多少个Valid Parentheses, 和领一道Leetcode的题一样. 求解卡特兰数的组成个数.
public class Solution { public List<Integer> diffWaysToCompute(String input) { List<Integer> res = new ArrayList<Integer>(); String opt = "+-*"; for(int i = 0; i < input.length(); i++) { if(opt.contains(""+input.charAt(i))){ String left = input.substring(0,i); String right = input.substring(i+1); List<Integer> leftList = diffWaysToCompute(left); List<Integer> rightList = diffWaysToCompute(right); for(Integer l : leftList) { for(Integer r : rightList) { if(input.charAt(i) == '+'){ res.add(l+r); }else if(input.charAt(i) == '-'){ res.add(l-r); }else if(input.charAt(i) == '*'){ res.add(l*r); }else{ res.add(0); } } } } } if(res.size() == 0) res.add(Integer.valueOf(input)); return res; } }
Leave A Comment