[LeetCode] 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".

((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]

解题思路

分而治之。对于输入字符串,若其中有运算符,则将其分为两部分,分别递归计算其值,然后将左值集合与右值集合进行交叉运算,将运算结果放入结果集中;若没有运算符,则直接将字符串转化为整型数放入结果集中。

实现代码

Java:

// Runtime: 6 ms
public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> res = new ArrayList<Integer>();
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (ch == '+' || ch == '-' || ch == '*') {
                List<Integer> left = diffWaysToCompute(input.substring(0, i));
                List<Integer> right = diffWaysToCompute(input.substring(i + 1));
                for (int n : left) {
                    for (int m : right) {
                        switch (ch) {
                        case '+':
                            res.add(n + m);
                            break;
                        case '-':
                            res.add(n - m);
                            break;

                        case '*':
                            res.add(n * m);
                            break;
                        }
                    }
                }
            }
        }

        if (res.size() == 0) {
            res.add(Integer.parseInt(input));
        }

        return res;
    }
}
时间: 2024-11-02 23:09:29

[LeetCode] Different Ways to Add Parentheses的相关文章

[LeetCode] Decode Ways II 解码方法之二

A message containing letters from A-Z is being encoded to numbers using the following mapping way: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

提高网页设计师的工作的价值的5个方法

网页制作Webjx文章简介:5种提高网页设计师价值的方法. 曾经作为独立的设计师工作过,深刻体验过国内设计行业市场的种种恶劣环境,低价竞争,套模板欺骗客户,抄袭现象,欺负客户不明真相等现象,真是深恶痛绝,在这样的恶劣环境下,设计师们怎么会有好作品的出现?恰巧看到篇<5 Ways to Add Value to Your Work as a Web Designer>,正是讲的是此情况,所以特地将里面的5个方法直接提取过来,希望同行们能够互勉.若能体会原汁原味请点击下面查看原文. 1. 停止恶劣

Common ASP.NET Code Techniques (DPC&amp;dwc Reference)

Figure 2.1Output of Listing 2.1.1 when viewed through a browser. Adding Elements to an ArrayListIn Listing 2.1.1 we create two ArrayList class instances, aTerritories and aStates, on lines 5 and 6, respectively. We then populate the aStates ArrayList

HOW TO: Update a Database from a DataSet Object Us

HOW TO: Update a Database from a DataSet Object Using Visual Basic .NETThis article discusses a Beta release of a Microsoft product. The information in this article is provided as-is and is subject to change without notice. No formal product support

创建吸引访问者的网站内容的14种方法

When I surf the Net, I often see web sites filled with beautiful graphics that strive to capture my attention. Well, they do so for an instant, however I click away when I don't immediately find relevant content. The content you add to your web site

HOW TO: Update a Database from a DataSet Object Using Visual Basic .NET

object|visual HOW TO: Update a Database from a DataSet Object Using Visual Basic .NETThis article discusses a Beta release of a Microsoft product. The information in this article is provided as-is and is subject to change without notice. No formal pr

Common ASP.NET Code Techniques (DPC&amp;amp;dwc Reference)--2

asp.net Figure 2.1Output of Listing 2.1.1 when viewed through a browser. Adding Elements to an ArrayListIn Listing 2.1.1 we create two ArrayList class instances, aTerritories and aStates, on lines 5 and 6, respectively. We then populate the aStates A

5个让网页设计师更有价值的方法

曾经作为独立的设计师工作过,深刻体验过国内设计行业市场的种种恶劣环境,低价竞争,套模板欺骗客户,抄袭现象,欺负客户不明真相等现象,真是深恶 痛绝,在这样的恶劣环境下,设计师们怎么会有好作品的出现?恰巧看到篇<5 Ways to Add Value to Your Work as a Web Designer>,正是讲的是此情况,所以特地将里面的5个方法直接提取过来,希望同行们能够互勉.若能体会原汁原味请点击下面查看原文. 1. 停止恶劣的价格竞争 Stop Racing to the Bott