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"
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

难度:medium

题目:给定一包含数字和操作符的字符串,计算并返回其所有数字与操作符组合的结果。有效的操作符为+,-,*

思路:类似unique binary tree, generate parentheses. 卡特兰数。

Runtime: 2 ms, faster than 84.52% of Java online submissions for Different Ways to Add Parentheses.

Memory Usage: 38.6 MB, less than 18.35% of Java online submissions for Different Ways to Add Parentheses.

class Solution {
    public List<Integer> diffWaysToCompute(String input) {

        return diffWaysToCompute(input, 0, input.length());
    }
    
    private List<Integer> diffWaysToCompute(String str, int start, int end) {
        if (!hasOperator(str, start, end)) {
            List<Integer> result = new ArrayList<>();
            result.add(Integer.parseInt(str.substring(start, end)));
            return result;
        }

        List<Integer> root = new ArrayList<>();
        for (int i = start; i < end; i++) {
            char c = str.charAt(i);
            if ('+' == c || '-' == c || '*' == c) {
                List<Integer> left = diffWaysToCompute(str, start, i);
                List<Integer> right = diffWaysToCompute(str, i + 1, end);
                
                for (Integer l: left) {
                    for (Integer r : right) {
                        if ('+' == c) {
                            root.add(l + r);
                        } else if ('-' == c) {
                            root.add(l - r);
                        } else if ('*' == c) {
                            root.add(l * r);
                        } 
                    }
                }
            }
        }
        
        return root;
    }
    
    private boolean hasOperator(String s, int start, int end) {
        for (int i = start; i < end; i++) {
            char c = s.charAt(i);
            if ('+' == c || '-' == c || '*' == c) {
                return true;
            }
        }
        
        return false;
    }
}

原文 

https://segmentfault.com/a/1190000018336381

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 241. Different Ways to Add Parentheses

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址