码迷,mamicode.com
首页 > 其他好文 > 详细

241. Different Ways to Add Parentheses

时间:2015-11-30 08:32:08      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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]

链接: http://leetcode.com/problems/different-ways-to-add-parentheses/

题解:

这题说是Different Ways to add parentheses,其实意思就是忽略运算符的优先级来计算算式。对此我们的解法是: 在算式valid的条件下,只要遇到运算符,我们就计算出左侧的数和右侧的数,然后根据这个运算符来得到结果。看discuss的时候发现Stefan Pochmann大神的解法...一行,擦,这哥们魔方还玩得很好,据说得过德国魔方比赛第一,是真牛。

Time Complexity - O(3n), Space Complexity - O(3n)

public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        if(input == null || input.length() == 0)
            return new ArrayList<Integer>();
        List<Integer> res = new ArrayList<>();
        
        for(int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if(c == ‘+‘ || c == ‘*‘ || c == ‘-‘) {
                List<Integer> l1 = diffWaysToCompute(input.substring(0, i));
                List<Integer> l2 = diffWaysToCompute(input.substring(i + 1));
                for( int x : l1) {
                    for(int y : l2) {
                        if(c == ‘+‘)
                            res.add(x + y);
                        else if(c == ‘-‘)
                            res.add(x - y);
                        else
                            res.add(x * y);
                    }
                }
            }
        }
        
        if(res.size() == 0)
            res.add(Integer.valueOf(input));
        return res;
    }
}

 

Reference:

https://leetcode.com/discuss/48468/1-11-lines-python-9-lines-c

https://leetcode.com/discuss/60626/share-a-clean-and-short-java-solution

https://leetcode.com/discuss/53566/python-easy-to-understand-solution-divide-and-conquer

https://leetcode.com/discuss/61840/java-recursive-9ms-and-dp-4ms-solution

https://leetcode.com/discuss/48477/a-recursive-java-solution-284-ms

https://leetcode.com/discuss/48488/c-4ms-recursive-%26-dp-solution-with-brief-explanation

https://leetcode.com/discuss/48494/what-is-the-time-complexity-of-divide-and-conquer-method

https://leetcode.com/discuss/55255/clean-ac-c-solution-with-explanation

 

241. Different Ways to Add Parentheses

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5006196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!